akif
akif

Reputation: 12324

Initialize list from array using a initializer list

A base class have readonly field of type List<SomeEnum> which the derived classes will initialize. Now, there is a derived class in which I want to add the all the values of the SomeEnum. One way is to type all the enum values, but the enum is a little big, so is there any other way to do it?

public class Base
{
 private readonly List<SomeEnum> _list;

 protected Base(List<SomeEnum> list)
 {
  _list = list;
 }
}

public class Derived : Base
{
 public Derived() : base(new List<SomeEnum>() { Enum.GetValues(typeof(SomeEnum)) }
 {
 }
}

(The above code would not compile, I believe intializers don't accept arrays.)

Upvotes: 1

Views: 1365

Answers (5)

Mark Byers
Mark Byers

Reputation: 837966

That won't work because the collection initializer calls Add with your argument, and you can't add an Array to a List using the Add method (you'd need AddRange instead).

However there is a constructor for List<T> can accept IEnumerable<T>. Try this:

new List<SomeEnum>((IEnumerable<SomeEnum>)Enum.GetValues(typeof(SomeEnum)))

Upvotes: 2

akif
akif

Reputation: 12324

base(new List<SomeEnum>(((IEnumerable<SomeEnum>)Enum.GetValues(typeof(SomeEnum)).GetEnumerator())))

I got it working by casting the enumerator returned to the generic type (which List accepts.)

Upvotes: 1

user47589
user47589

Reputation:

It's because you have to cast the result of Enum.GetValues to the appropriate IEnumerable<T> type. See here:

using System.Linq;


public class Derived : Base
{
    public Derived()
        : base(new List<SomeEnum>(Enum.GetValues(typeof(SomeEnum)).OfType<SomeEnum>()))
    {
    }
}

Upvotes: 4

vc 74
vc 74

Reputation: 38179

As Mark wrote, there is a List constructor that accepts an enumerable, maybe you can leverage it the following (less coupled) way:

public class Base 
{     
  private readonly List<UserActions> _list;      

  protected Base(IEnumerable<UserActions> values)
  {         _list = new List<UserActions>(values);  
  } 
}  

public class Derived : Base 
{     
   public Derived() : base((UserActions[]) Enum.GetValues(typeof(UserActions))
  { 
  }
} 

Upvotes: 2

David Conde
David Conde

Reputation: 4637

Did you tried passing the array of values in the constructor of the list, like this:

public Derived() : 
         base(new List<SomeEnum>(Enum.GetValues(typeof(UserActions))) 
{}

Upvotes: 1

Related Questions