문제

I have a problem since I just learned about accessors, I want to learn how to let it work with arrays, this is my script

public Vak[] vakken = new Vak [5];

the class I use to create the accessors is the next one:

public class Vak
{
public string name {get; set;}
public string docent {get; set;}
public int uren {get; set;}
}

and in my button click event this is how I want to set it by this command and I don't know why it's givving me the null reference error.

vakken[0].name = "Joe";

Thanks for any help!

도움이 되었습니까?

해결책

That happens because you do not instantiate your class. When you create the array of Vaks, make a for loop just after it to instantiate every element like this:

for (int i = 0; i < vakken.Length; i++)
{
     vakken[i] = new Vak(); // this basically allocates memory for your object
}

Than you can change the values of every single property of every element in that array.

To clarify, using the new keyword you invoke the constructor which is basically method-like block of code which is being executed when you instantiate your class. In your class you did not define a constructor. If you do that the compiler creates a default parameterless constructor which I used in order to create an instance of every single element of your array.

다른 팁

You only initialized the array but no value of the array.

You also have to use:

vakken[0] = new Vak();

And also for all other elements (you can do this in a loop for example)

You initialized the array, but you haven't initialized each item in the array. Try:

vakken[0] = new Vak();
vakken[0].name = "Joe";
vakken[1] = new Vak();
vakken[1].name = "Dave";
//etc
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top