Different array value from different function [duplicate] - c#

This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed 3 years ago.
I'm still learning about Unity and trying to create some simple games.. but i got a same error for a few days when i tried to fill array from public function.. it said that my index was outside the bounds of array..
is there anything related with public or not?
i do know about the cause of this error. what iam asking is why it gives different value from different function(same script)?
please help :d (sorry for my bad english)
this is my code :
public void PencetTombol()
{
//this is where i got error line
prefab[0].GetComponentInChildren<Text>().text = "test";
}
void cekkata()
{
//this code works
prefab[0].GetComponentInChildren<Text>().text = "test";
}
void buat_kotak()
{
pindah = false;
var test = "CHELSEA";
prefab = new GameObject[test.Length];
for (int i = 0; i < test.Length; i++)
{
if (test[i] != ' ')
{
prefab[i] = Instantiate(prefab2, new Vector3(0.5f, 0.5f, 0.5f), Quaternion.identity);
if (pindah == false)
{
prefab[i].transform.SetParent(panelatas.transform, false);
}
else
{
prefab[i].transform.SetParent(paneltengah.transform, false);
}
}
else
{
pindah = true;
}
}
}

Your error has no connection with access modifiers.
This error is thrown when you try to access an array element that does not yet exist.
Example:
string[] test = { "test" };
var x = test[0]; --> success
var y = test[1]; --> out of bounds

Related

Return Empty Array in C# If Index In Loop is Out Of Range [duplicate]

This question already has an answer here:
Index Error in C# Where Array Should Return Empty Array But Returns Out Of Range
(1 answer)
Closed 2 years ago.
I'm new to C# and what I want to do here is add a conditional to return an empty array if the loop that I have set for my DataPoints API response variable is out of range.
Right now it throws an exception but what I want it to do is instead of throwing the exception just return an empty array in the DataPoints API response. How would I do that?
exception
"Index was out of range. Must be non-negative and less than the size
of the collection.\r\nParameter name: index""
code sample
public void BuildDataPoints()
{
// Create WspViewList from ViewData
WspViewList dataPointBuilder = new WspViewList(ViewData);
List<DataPointAPI> dataset = new List<DataPointAPI>();
WspViewCol _labelCol = null;
List<WspViewCol> yAxisCols = new List<WspViewCol>();
//Iterate through the view's columns to find special chart columns
foreach (WspViewCol col in dataPointBuilder._cols)
{
if (col._baseCol.DbrViewCol.YAxis)
yAxisCols.Add(col);
if (col._baseCol.DbrViewCol.XAxis)
_labelCol = col;
}
var DataPoints = new DataPoints();
// Generate DataPoints (or something similar) from the newly constructed WspViewList.
foreach (WspViewRow row in dataPointBuilder)
{
var dataPointList = row.OriginalData.TrimStart('[').TrimEnd(']').Split(',').ToList();
for (var index = 2; index < dataPointList.Count; index++)
{
var dataPoint = dataPointList[index];
if (string.IsNullOrEmpty(dataPoint))
continue;
ChartDataObject cdo;
if (DataPoints.datasets.Count <= index - 2)
{
cdo = new ChartDataObject();
DataPoints.datasets.Add(cdo);
cdo.label = ColumnObjects[index].propertyName;
}
else
cdo = DataPoints.datasets[index - 2];
cdo.data.Add(dataPoint);
<—-THIS LINE THROWS THE ERROR —>
DataPoints.datasets[index - 2] = cdo;
}
DataPointAPI DataPointResponse = new DataPointAPI()
{
data = DataPoints,
};
dataset.Add(DataPointResponse);
}
// Set some class field to contain these datapoints
ChartData = dataset;
}
public class DataPointAPI
{
public DataPoints data;
}
public class DataPoints
{
public List<string> labels { get; set; }
public List<ChartDataObject> datasets { get; set; }
public DataPoints()
{
labels = new List<string>();
datasets = new List<ChartDataObject>();
}
}
public class ChartDataObject
{
public string label { get; set; }
public List<string> data { get; set; }
public ChartDataObject()
{
data = new List<string>();
}
}
Before whichever line of code causes the error, put something like:
if(someIndex >= someArray.Length)
return new someType[someLengthYouWantTheNewArrrayToHave];
Change the names for whatever is relevant to your code (it isn't really easy to see which line of code throws this error you encounter). It's also not clear to me what you mean by "empty array" - usually it's either an array with length 0, bllut people sometimes mean an array where every element is null or zero. The essential logic is "if the index is at or greater than the array length, you're about to crash so do something else instead, like returning new string[2]". You'll also need to make sure that the return type of the method your code is in matches the type of the array you return.
I didn't recommend catching the exception because exceptions are expensive. If you can prevent raising them by detecting when you're about to access an array/collectionnusing an index that is greater than its length, then you should rather than trying code you know will crash and catching. Using exceptions for normal control flow is generally a no-no
Declare a function that does the job:
public DataPointAPI ProcessWspViewRow(WspViewRow) {
DataPointAPI DataPointResponse = new DataPointAPI();
var dataPointList = row.OriginalData.TrimStart('[').TrimEnd(']').Split(',').ToList();
if (dataPointList.Count < 2) {
// Assign here DataPointResponse.data = new DataPoints();
return DataPointResponse;
}
DataPoints.labels.Add(dataPointList[1]);
for (var index = 2; index< dataPointList.Count; index++)
{
var dataPoint = dataPointList[index];
if (string.IsNullOrEmpty(dataPoint))
continue;
ChartDataObject cdo;
if (DataPoints.datasets.Count <= index - 2)
{
cdo = new ChartDataObject();
DataPoints.datasets.Add(cdo);
cdo.label = ColumnObjects[index].propertyName;
}
else
cdo = DataPoints.datasets[index - 2];
cdo.data.Add(dataPoint);
DataPoints.datasets[index - 2] = cdo;
}
DataPointResponse.data = DataPoints;
return DataPointResponse
}
Your code now becomes:
foreach (WspViewRow row in dataPointBuilder)
{
dataset.Add(ProcessWspViewRow(row);
}
Try this:
try
{
// your code
}
catch (IndexOutOfRangeException)
{
return Array.Empty<T>();
}
Where T is type of your array element.

C# Object reference null but not null [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
The forum is full of posts about problems like this. I've red some but didn't manage to solve my own problem.
I get Exception error:
Object reference not set to an instance of an object.
try
{
CZaposleni zap = new CZaposleni();
zap.Sifra = "1234567894567";
zap.Ime = "testIme";
zap.Prezime = "testPrezime";
zap.Pol = Char.Parse("M");
zap.JMBG = "1234567899871";
zap.Brknjizice = "12345";
zap.SS = "4.test";
zap.DatumR = DateTime.Parse("4/11/2013");
zap.DatumZ = DateTime.Parse("4/11/2013");
zap.Mestorodj = "testMesto";
zap.Prebivaliste = "testPrebivaliste";
zap.Kontakt1 = "654987";
zap.Kontakt2 = "564845";
CRadnaMesta rad = new CRadnaMesta();
rad.ID = Int32.Parse(cbRadnaMesta.SelectedValue.ToString());
Console.WriteLine("Zap = "+zap.ID +" Rad = "+rad.ID);
zap.Radnomesto = rad;
Console.WriteLine("Zap check 1: " + zap.ID + " " + zap.Radnomesto.ID);
zap.dodajRadnika();
Console.WriteLine("Zap check 2: "+zap.ID+" "+zap.Radnomesto.ID);
}
catch (Exception ex)
{
MessageBox.Show("Frm: "+ex.Message);
}
The code breaks at 'zap.Radnomesto = rm;' since last output when running the code i get is
rm.ID = 1
zap.ID = 0
So none of two objects is null.
I believe your error is in the CZaposleni class in the following code:
public CRadnaMesta Radnomesto
{
get
{
return radnomesto;
}
set
{
if ( radnomesto.ID == 0 )
throw new Exception("Morate uneti radno mesto.");
radnomesto = value;
}
}
More precisely in if ( radnomesto.ID == 0 ). Since radnomesto is null if not set, you're getting the error while checking for the ID.
You should use the following code instead:
public CRadnaMesta Radnomesto
{
get
{
return radnomesto;
}
set
{
if ( value == null || value.ID == 0 )
throw new Exception("Morate uneti radno mesto.");
radnomesto = value;
}
}

Setting Background Color Of Button in WPF on runtime [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 6 years ago.
I am trying to set Background Color of Button(Names: b0,b1,b2,b3,b4,b5,b6,b7,b8,b9) in WPF on runtime.
Color Name is getting from Database that is Red right now. But it's giving me System.NullReferenceExceptionn: Object reference not set to an instance of an object
private void ButtonBgColor()
{
string qryBgColor = "select Name from lookup where code in (select VALUE from qSettings where name='BUTTON_BG_COLOR') and type='BgColor'";
try
{
sqlConnection.Open();
sqlCommand = new SqlCommand(qryBgColor, sqlConnection);
sqlDataReader = sqlCommand.ExecuteReader();
if (sqlDataReader.Read())
{
string BUTTON_BG_COLOR = sqlDataReader["Name"].ToString();
Button[] b = new Button[9];
for (int i = 0; i < b.Length; i++)
{
var textBlock08 = (TextBlock)b[i].Template.FindName("myTextBlock", b[i]);
textBlock08.Background = (System.Windows.Media.SolidColorBrush)new System.Windows.Media.BrushConverter().ConvertFromString(BUTTON_BG_COLOR);
}
}
}
catch (Exception exp)
{
MessageBox.Show(exp.ToString(), "Button Background Color Exception");
}
Can anyone help me to resolve this problem ?
Thanks in advance
You haven't assigned anything to b. It's just an empty array. Therefore, calling b[i] will always result in a null-ref.

Waiting for a parse.com async task to finish in Unity3D

As part of my school project I'm trying to link two tables to decrease the amount of data stored in one table so I wanted to link my "Scores" class with my "CorrectAnswers" class via the ObjectID. However since the tasks are asynchronous, by the time one task is done saving, the other task has already begun or also finished saving and so the ObjectID returns as null.
Here's the code I'm using:
public void SaveScore()
{
ParseObject SendScore = new ParseObject("Scores");
SendScore["Score"] = CheckAnswer.score;
SendScore["user"] = ParseObject.CreateWithoutData("_User", ParseUser.CurrentUser.ObjectId);
SendScore["TestMode"] = MainMenu.testmode;
SendScore["TotalQuestions"] = QuestionCreation.TotalQuestions;
SendScore["CorrectQuestions"] = CheckAnswer.CorrectQuestions;
SendScore.SaveAsync().ContinueWith(t =>
{
ScoreObjectId = SendScore.ObjectId;
});
ParseObject SendCorrectTopics = new ParseObject("CorrectAnswers");
SendCorrectTopics["Score"] = SendScore.ObjectId;
for (int i = 0; i <= 9; i++)
{
string Topic = "Topic" + (i + 1).ToString();
SendCorrectTopics[Topic] = CheckAnswer.CorrectTopics[i];
}
SendCorrectTopics.SaveAsync();
SceneManager.LoadScene(0);
}
How would I be able to make the second save hold until the first save has finished? I'm somewhat new to C# and so don't quite know all it's features yet. I've looked into "await" but unity doesn't seem to like that. Any help would be greatly appreciated!
Thanks in advance,
EDIT: Okay, after a bit more reading on Unity's coroutines, I found a much better way of checking that only relies on checking when needed:
IEnumerator CheckSave()
{
while(ScoreObjectId == null & !DoneSave))
{
print("Running");
yield return new WaitForSeconds(0.5f);
}
DoneSave = false;
SaveTotalTopics();
}
This seems like a much better way of doing it.
Well, it seems the answer was something I've already done before, even if it is a little ugly.
Using Unity's update function I created a check to make sure the ObjectID is not null and the previous save had completed, as so:
void Update () {
if (ScoreObjectId != null & DoneSave)
{
DoneSave = false;
SaveTotalTopics();
}
Thus splitting it into two saves and creating:
public void SaveScore()
{
ParseObject SendScore = new ParseObject("Scores");
SendScore["Score"] = CheckAnswer.score;
SendScore["user"] = ParseObject.CreateWithoutData("_User", ParseUser.CurrentUser.ObjectId);
SendScore["TestMode"] = MainMenu.testmode;
SendScore["TotalQuestions"] = QuestionCreation.TotalQuestions;
SendScore["CorrectQuestions"] = CheckAnswer.CorrectQuestions;
Task SendingScores = SendScore.SaveAsync().ContinueWith(t =>
{
if (t.IsFaulted || t.IsCanceled)
{
DoneSave = false;
print(t.Exception);
}
else
{
DoneSave = true;
print("Setting object ID!");
ScoreObjectId = SendScore.ObjectId;
print(ScoreObjectId);
}
});
}
void SaveTotalTopics()
{
for (int i = 0; i <= 9; i++)
{
string Topic = "Topic" + (i + 1).ToString();
SendCorrectTopics[Topic] = CheckAnswer.CorrectTopics[i];
}
SendCorrectTopics["UserScore"] = ParseObject.CreateWithoutData("Scores", ScoreObjectId);
SendCorrectTopics.SaveAsync().ContinueWith(t =>
{
if(t.IsFaulted || t.IsCanceled)
{
print(t.Exception);
}
else
{
print("Saved!");
}
});
}
I'd also forgotten to use ParseObject.CreateWithoutData() so my first code snippet wouldn't have worked even if I'd found a better method...
So, although I'm not happy with the final result, at least it works and I don't think running an if statement every frame should significantly impact on my game's performance.
Why not use a bool and a while loop?
public IEnumerator SaveScore()
{
bool canContinue = false;
ParseObject SendScore = new ParseObject("Scores");
SendScore["Score"] = CheckAnswer.score;
SendScore["user"] = ParseObject.CreateWithoutData("_User", ParseUser.CurrentUser.ObjectId);
SendScore["TestMode"] = MainMenu.testmode;
SendScore["TotalQuestions"] = QuestionCreation.TotalQuestions;
SendScore["CorrectQuestions"] = CheckAnswer.CorrectQuestions;
SendScore.SaveAsync().ContinueWith(t =>
{
ScoreObjectId = SendScore.ObjectId;
//set the bool canContinue to true because the first portion of code has finished running
canContinue = true;
});
//wait while the canContinue bool is false
while(!canContinue){
yield return null;
}
//continue your parse code
ParseObject SendCorrectTopics = new ParseObject("CorrectAnswers");
SendCorrectTopics["Score"] = SendScore.ObjectId;
for (int i = 0; i <= 9; i++)
{
string Topic = "Topic" + (i + 1).ToString();
SendCorrectTopics[Topic] = CheckAnswer.CorrectTopics[i];
}
SendCorrectTopics.SaveAsync();
SceneManager.LoadScene(0);
return null;
}

C# - NullReferenceException when attempting to parse a string to float in an array [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 7 years ago.
This is blowing my mind right now, I don't know what I'm doing wrong.
What I'm attempting to do is grab the contents of a textbox, splitting values separated by a comma, putting them into an array and then parsing them to float and put them into another array.
System.NullReferenceException: Object reference not set to an instance of an object.
Xt = s1.Split(',').Select(s1V => s1V.Trim()).ToArray();
Yt = s2.Split(',').Select(s2V => s2V.Trim()).ToArray();
float number;
if (Xt.Length == Yt.Length)
{
int i = 0;
foreach (var value in Xt)
{
// Console.WriteLine("l:"+Xt.Length+" "+Xt[i]+"+");
if (Xt[i] != null)
{
Xi[i] = float.Parse(Xt[i]);
}
// Yi[i] = float.Parse(Yt[i]);
i++;
}
...
string s1 = textBox1.Text;
string s2 = textBox2.Text;
float[] Yi;
Xt = s1.Split(',').Select(s1V => s1V.Trim()).ToArray();
Yt = s2.Split(',').Select(s2V => s2V.Trim()).ToArray();
float number;
if (Xt.Length == Yt.Length)
{
int i = 0;
Xi = new float[Xt.Length];//<---properly initializing the array.
foreach (var value in Xt)
{
// Console.WriteLine("l:"+Xt.Length+" "+Xt[i]+"+");
if (Xt[i] != null)
{
Xi[i] = float.Parse(Xt[i]);
}
// Yi[i] = float.Parse(Yt[i]);
i++;
}
Thanks to MarcinJuraszek.

Categories