Only a Curious Mind
Only a Curious Mind

Reputation: 2857

How to add enum in generic lists

How can I add only one enum item in a generic list?

public List<T> PopuleList<T>() where T : struct
{
    List<T> list = new List<T>();

    if (typeof(T) == typeof(ProcessorEnum))
    {
        list.AddRange(Enum.GetValues(typeof(T)) as IEnumerable<T>); // This work, but I need to add only one value.

        list.Add(ProcessorEnum.B2B); // <- I need like this, but this give-me a compile error.
    }

    return list;
}

Upvotes: 0

Views: 495

Answers (4)

Servy
Servy

Reputation: 203814

In this case the list needs to be a list of ProcessorEnum values. The method is not in fact generic because it cannot accept any type of list. You should simply make the method non-generic:

public List<ProcessorEnum> PopuleList()
{
    return new List<ProcessorEnum>(){ProcessorEnum.B2B};
}

Upvotes: 0

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73442

As @Selman shows in his answer, you can cast it to object then to T but this involves "Boxing and UnBoxing". You can avoid boxing and unboxing using this

list.Add((ProcessorEnum.B2B as T?).Value);

Upvotes: 0

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101681

You can use double cast like this:

list.Add((T)(object)ProcessorEnum.B2B);

Upvotes: 3

MarcinJuraszek
MarcinJuraszek

Reputation: 125620

Cast to List<ProcessorEnum> before calling Add:

(list as List<ProcessorEnum>).Add(ProcessorEnum.B2B);

Upvotes: 0

Related Questions