GabeMeister
GabeMeister

Reputation: 1868

Instantiating an IEnumerable array in C#

I was wondering why you can do this in C#:

IEnumerable<int>[] nums = new IEnumerable<int>[10];

but cannot do this:

IEnumerable<int> nums = new IEnumerable<int>();

What is C# doing under the hood with the first statement? I thought you couldn't create instances of interfaces with the new keyword.

Upvotes: 4

Views: 10082

Answers (2)

Joakim Skoog
Joakim Skoog

Reputation: 786

You are correct in that you can't create instances of interfaces in C#. The difference between the two statements is that in the first statement you are creating an array of IEnumerable<int>, which is allowed.

The second statement would work if you create an instance of a class that implements the IEnumerable<T> interface, such as List<T>.

An example of doing this is: IEnumerable<int> numbers = new List<int> {1,2,3};;

You could also do: IEnumerable<int> numbers = new int[] {1, 2, 3}

Upvotes: 14

Yacoub Massad
Yacoub Massad

Reputation: 27861

The first statement is creating a new array of size 10 of which item type is IEnumerable<int>. The array itself is a concrete type that you can create.

To set an item in this array, you would do something like this:

num[0] = new List<int>() {1,2,3};

Although the item type is IEnumerable<int>, you cannot create an instance of IEnumerable<int>. You would have to create an instance of a class that implements IEnumerable<int> like List<int>.

In the second example, you try to create an instance of IEnumerable<int> which is an interface, i.e. not class, and so it would not compile.

The variable type can still be IEnumerable<int>, but you would have to create an instance of a class that implements IEnumerable<int> like this:

IEnumerable<int> nums = new List<int>() {1,2,3};

Upvotes: 6

Related Questions