Question

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!

Was it helpful?

Solution

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.

OTHER TIPS

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top