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...
C# |
C# |
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
JureRank #2,128 · 670 reputationPosted Nov 6, 2010, 7:28 AM EDT
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.
JureRank #2,128 · 670 reputationPosted Nov 5, 2010, 2:43 PM EDT
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).
Elod Horvath11 reputationPosted Nov 6, 2010, 3:30 AM EDT
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!
Elod Horvath11 reputationPosted Nov 7, 2010, 5:23 AM EST
this is really information overload, I must learn much it seems.
Thanx,
good byte!
Suthish NairRank #92 · 22.8K reputationPosted Nov 7, 2010, 10:27 PM EST