2

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!

Diederik
  • 79
  • 1
  • 12
  • possible duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Soner Gönül May 03 '14 at 17:13

3 Answers3

1

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)

Flat Eric
  • 7,971
  • 9
  • 36
  • 45
1

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.

Lynx
  • 506
  • 2
  • 10
0

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
Dave Zych
  • 21,581
  • 7
  • 51
  • 66