I want to create an array of my class Word. Here is the code:
public static void Main(string[] args)
{
Word[] Wörter = new Word[5];
Wörter[0]._Word_ = "Hallo";
Wörter[1]._Word_ = "Flugzeug";
Wörter[2]._Word_ = "Automobil";
Wörter[3]._Word_ = "Musikanlage";
Wörter[4]._Word_ = "Steuerung";
}
public class Word
{
private string _Word;
private int _counter;
public string _Word_
{
get
{
return _Word;
}
set
{
_Word = value;
}
}
public int _counter_
{
get
{
return _counter;
}
set
{
_counter = 0;
}
}
}
I always get a System.NullReferenceException in this line
Wörter[0]._Word_ = "Hallo";
If I call the an instance of my class(without array), everything works fine. I think I got a problem with the array. Maybe is using an array in this situation not the best think to do. Thank you for helping!
The problem is that you're creating an array, but that array contains empty references to start with - you're never creating any instances of Word
. You want something like:
Word[] Wörter = new Word[5];
Wörter[0] = new Word();
Wörter[0]._Word_ = "Hallo";
// etc
However, you can reduce the code to achieve the same effect using object initializers:
Word[] Wörter = new Word[5];
Wörter[0] = new Word { _Word_ = "Hallo" };
...
And then you can use an array initializer to do the whole thing in one statement:
Word[] Wörter =
{
new Word { _Word = "Hallo" },
new Word { _Word_ = "Flugzeug" },
new Word { _Word_ = "Automobil" },
new Word { _Word_ = "Musikanlage" },
new Word { _Word_ = "Steuerung"}
};
The next step in my view would be to start following .NET naming conventions, calling your properties Text
and Counter
(you can't call the property Word
as that's the name of the class), using automatically implemented properties to reduce cruft further, and then adding a constructor taking the initial value of the property in the constructor:
public class Word
{
public string Text { get; set; }
public int Counter { get; set; }
public Word(string text)
{
Text = text;
}
}
Word[] words =
{
new Word("Hallo"),
new Word("Flugzeug"),
new Word("Automobil"),
new Word("Musikanlage" )
new Word("Steuerung")
};
Doesn't that look better? :)
You might also want to make the Text
property read-only. Until C# 6 lands that means either keeping a private setter or using a "manually implemented" property, but in C# 6 you'll be able to write:
public string Text { get; }
and just assign it in the constructor.
Additionally, you need to think about whether you really need an array at all. Often using a List<T>
offers significantly more flexibility.
See more on this question at Stackoverflow