views:

106

answers:

4

I have enum:

    public enum SymbolWejsciowy
{
     K1 , K2 , K3 , K4 , K5 , K6 , K7 , K8 
}

and I want to create list of this enum

 public List<SymbolWejsciowy> symbol;

but in my way to add enum to List:
1.

SymbolWejsciowy symbol ;  
symbol.Add(symbol = SymbolWejsciowy.K1); 

2.
symbol.Add(SymbolWejsciowy.K1);

I always get Exception

Object reference not set to an instance of an object.

What i do wrong :/ Please help :)

+3  A: 

In your option 1 SymbolWejsciowy instance and your list have the same name, I imagine that's a typo error.

Without taking that into account I'd say you didn't created the instance of the list

symbol = new List<SymbolWejsciowy>();
Claudio Redi
+2  A: 

Your code never initializes the list. Try this:

public List<SymbolWejsciowy> symbol = new List<SymbolWejsciowy>();
symbol.Add(SymbolWejsciowy.K1);

and

SymbolWejsciowy mySymbol= SymbolWejsciowy.K2;
symbol.Add(mySymbol);
msergeant
+3  A: 

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();
Mark Byers
I never realized that i do that mistake! Yes, i don't initialize the list ... Thanks!
netmajor
A: 

It sure would be nice if Enum.GetValues() had been updated for generics way back in C# 2.0. Well, guess we have to write it ourselves:

static class EnumHelpers<T> where T : struct
{
    public class NotAnEnumException : Exception
    {
        public NotAnEnumException() : base(string.Format(@"Type ""{0}"" is not an Enum type.", typeof(T))) { }
    }

    static EnumHelpers()
    {
        if (typeof(T).BaseType != typeof(Enum)) throw new NotAnEnumException();
    }

    public static IEnumerable<T> GetValues()
    {
        return Enum.GetValues(typeof(T)).Cast<T>();
    }

    public static T Parse(string value)
    {
        return (T)Enum.Parse(typeof(T), value);
    }
}

I included Parse() because it benefits from generics in the same way.

Usage:

        var symbols = EnumHelpers<SymbolWejsciowy>.GetValues().ToList();

        SymbolWejsciowy s = EnumHelpers<SymbolWejsciowy>.Parse("S2");

(ASIDE: I also wish you could write where T : enum for just this sort of thing. Also, where T : delegate.)

Jay Bazuzi