I came a cross some difficulty with my object.
Im trying to have an array of object (Question) that I’ve created:
public class Question
{
public int id = 0;
public string question = string.Empty;
public string a1 = string.Empty;
public string a2 = string.Empty;
public string a3 = string.Empty;
public string a4 = string.Empty;
public int Tanswer = 0;
}
and Now Im trying to set some values in it like this :
Question[] arr = new Question[4];
Random rnd = new Random();
int i = 0;
int temp = 0;
bool ok = false;
while (i < 3)
{
temp = rnd.Next(0, Int32.Parse(dt_count.Rows[0][0].ToString()) - 1);
for (int j = 0; j < arr.Length; j++)
{
arr[j].id = Int32.Parse(dt_q_notMust.Rows[temp][0].ToString()); // ID
arr[j].question = dt_q_notMust.Rows[temp][1].ToString(); // Question
arr[j].a1 = dt_q_notMust.Rows[temp][2].ToString(); // A1
arr[j].a2 = dt_q_notMust.Rows[temp][3].ToString(); // A2
arr[j].a3 = dt_q_notMust.Rows[temp][4].ToString(); // A3
arr[j].a4 = dt_q_notMust.Rows[temp][5].ToString(); // A4
arr[j].Tanswer = Int32.Parse(dt_q_notMust.Rows[temp][6].ToString()); // True Answer (int).
if (arr[j].id != temp)
{
ok = true;
}
}
if (ok)
{
i++;
}
}
and its write an error for some reason, like I’ve been never initialize it :
Object reference not set to an instance of an object.
but I did wrote the :
Question[] arr = new Question[4];
so I wonder whats the problem is ?
Thanks!
You’ve initialised
arras a new array, but all of its elements are still null. You need to initialise each item before you access it: