Reputation: 2857
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
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
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
Reputation: 101681
You can use double cast like this:
list.Add((T)(object)ProcessorEnum.B2B);
Upvotes: 3
Reputation: 125620
Cast to List<ProcessorEnum>
before calling Add
:
(list as List<ProcessorEnum>).Add(ProcessorEnum.B2B);
Upvotes: 0