could you enlighten me what may cause a NullReferenceException in the code below? I tried to create an array of my own ("student") class, but in vain it seems...
|
|
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
JurePosted Nov 6, 2010, 11:28 AM
If it's an array of objects, all elements are "empty references" - references to nothing. And reference to nothing is "null". Consider this:
student sample = new student("aaa", rand.Next(1, 6));
student[] array = new student[5];
array[3] = sample; // student[3] becomes reference to sample
array[3].name = "bbb"; // change sample's name trough that reference
Console.WriteLine(sample.name); // outputs sample's name, which is now "bbb"
Objects are always considered a reference. For example, if you pass an object to a function, it won't create new instance (a copy), but will simply pass a reference to that object. So changing the passed object in function's body will actually change the object itself.
This is different from passing a variable of type int, where only its value is passed.
Suthish NairPosted Nov 8, 2010, 3:27 AM
Elod HorvathPosted Nov 7, 2010, 10:23 AM
this is really information overload, I must learn much it seems.
Thanx,
good byte!
Elod HorvathPosted Nov 6, 2010, 7:30 AM
Really helpful it was.
I tried your first method, with the constructor and it worked.
So, as a conclusion arrays of class instances must have 2 new instructions: 1 for creating the whole array and 1 for each element in the array. If I am right...
Thanx for much help, have fun!
JurePosted Nov 5, 2010, 6:43 PM
One way is to make a constructor for student class that sets note and name member. Put this into student class:
public student(string name, byte note)
{
this.name = name;
this.note = note;
}
Then you can write:
for (int i = 0; i < students.Length; ++i)
{
students[i] = new student("aaa", (byte)rand.Next(1, 6));
}
Another way is to make name and note into properties (but you don't need to write constructor):
Replace public string name; with public string name { get; set; },
and replace public byte note; with public byte note { get; set; }
Using the above loop, you can now write:
for (int i = 0; i < students.Length; ++i)
{
students[i] = new student { name = "aaa", note = (byte)rand.Next(1, 6) };
}
The last version is more flexible, because you can choose which properties you want to set.
Anyway, the point is that element(s) must be a reference to an instance of an object (of class "student" in your case), if you want to use the elements as objects.
So, you must use keyword new for each element (assuming you want every element to be unique instance).