I have the following enum:
public enum SymbolWejsciowy
{
K1 , K2 , K3 , K4 , K5 , K6 , K7 , K8
}
I want to create a list using the values of this enum:
public List<SymbolWejsciowy> symbol;
I have tried a couple different ways to add the enum values to the list:
SymbolWejsciowy symbol;
symbol.Add(symbol = SymbolWejsciowy.K1);
and
symbol.Add(SymbolWejsciowy.K1);
However, I always get the following exception:
Object reference not set to an instance of an object.
How can I correctly accomplish this?
As other answers have already pointed out, the problem is that you have declared a list, but you haven’t constructed one so you get a
NullReferenceExceptionwhen you try to add elements.Note that if you want to construct a new list you can use the more concise collection initializer syntax:
If you want a list containing all the values then you can get that by calling
Enum.GetValues: