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?
The idea is to use the Enum. GetValues() method to get an array of the enum constants' values. To get an IEnumerable<T> of all the values in the enum, call Cast<T>() on the array. To get a list, call ToList() after casting.
Yes. If you do not care about the order, use EnumSet , an implementation of Set . enum Animal{ DOG , CAT , BIRD , BAT ; } Set<Animal> flyingAnimals = EnumSet.
Use a list comprehension to get a list of all enum values, e.g. values = [member. value for member in Sizes] . On each iteration, access the value attribute on the enum member to get a list of all of the enum's values.
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 NullReferenceException
when you try to add elements.
Note that if you want to construct a new list you can use the more concise collection initializer syntax:
List<SymbolWejsciowy> symbols = new List<SymbolWejsciowy>
{
SymbolWejsciowy.K1,
SymbolWejsciowy.K2,
// ...
};
If you want a list containing all the values then you can get that by calling Enum.GetValues
:
List<SymbolWejsciowy> symbols = Enum.GetValues(typeof(SymbolWejsciowy))
.Cast<SymbolWejsciowy>()
.ToList();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With