Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add enum values to a list

Tags:

c#

list

enums

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?

like image 218
netmajor Avatar asked May 30 '10 22:05

netmajor


People also ask

How do I add an enum to a list?

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.

Can we add list to enum?

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.

How do I get all the values in an enum list?

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.


1 Answers

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();
like image 97
Mark Byers Avatar answered Oct 12 '22 12:10

Mark Byers