137

I want to create a new instance of an object IEnumerable<object>

Can I do this?

IEnumerable<object> a = new IEnumerable<object>();
aloisdg
  • 22,270
  • 6
  • 85
  • 105
WingMan20-10
  • 3,594
  • 9
  • 31
  • 42
  • Related: http://stackoverflow.com/questions/191013/can-a-c-anonymous-class-implement-an-interface – Josh Lee Jan 05 '11 at 16:22
  • Please clarify your question. That line of code won't compile, as I'm sure you've discovered already. If you could give us more information about what you're actually trying to achieve, that would help us to answer you. – Jon Skeet Jan 05 '11 at 16:25
  • I wanted to create a new enumerable object or list and be able to add to it. – WingMan20-10 Jan 05 '11 at 16:32
  • 3
    @WingMan20-10: Well, that changes EVERYTHING. You can't add to a generic `IEnumerable`. You have to use something like `List`. – jason Jan 05 '11 at 16:37
  • 1
    In this case you need a concrete array List objs = new IEnumerable. You cannot add items to an iterator because it's not a collection ... its an iterator:) – user44298 Jan 05 '11 at 16:38
  • 1
    @ivo: Note that `IEnumerable` doesn't represent an iterator - it represents an *iterable* sequence. `IEnumerator` itself represents the iterator. – Jon Skeet Jan 05 '11 at 17:09
  • Thanks Jon, I'm aware of it - http://stackoverflow.com/questions/4514538/why-can-iterators-in-structs-modify-this/4571612#4571612 :) But don't want to confuse the person. – user44298 Jan 05 '11 at 17:23
  • can ienumerable deal with different datatypes of objects or same like IEnumerable need answer – nouman arshad May 29 '15 at 06:38

11 Answers11

160

You can for example create an instance of List<object>, which implements IEnumerable<object>. Example:

List<object> list = new List<object>();
list.Add(1);
list.Add(4);
list.Add(5);

IEnumerable<object> en = list;
CallFunction(en);
dcastro
  • 66,540
  • 21
  • 145
  • 155
Stefan Schultze
  • 9,240
  • 6
  • 35
  • 42
  • 14
    Given that the question shows the use of generics, given an example of a type that doesn't implement the generic `IEnumerable` is a bad idea IMO. – Jon Skeet Jan 05 '11 at 16:24
  • Any problem with using CallFunction(list.AsEnumerable()) instead of IEnumerable en = list;... – Gina Marano Jun 18 '14 at 23:18
  • 1
    I'd use an array with literal initializer if possible, it's the most efficient and lightweight enumerable type available in .NET and doesn't have the overhead of a List<>. Lists should only be used if you really need or want to mutate after initialization. Also, it's better to add System.Linq and invoke .AsEnumerable() on the array or list. – Mark Jun 27 '18 at 14:00
73

Another solution would be to use Empty<T>.

msdn extract:

Returns an empty IEnumerable that has the specified type argument.

IEnumerable<object> a = Enumerable.Empty<object>();

There is a thread on SO about it: Is it better to use Enumerable.Empty() as opposed to new List to initialize an IEnumerable?

If you use an empty array or empty list, those are objects and they are stored in memory. The Garbage Collector has to take care of them. If you are dealing with a high throughput application, it could be a noticeable impact.

Enumerable.Empty does not create an object per call thus putting less load on the GC.

aloisdg
  • 22,270
  • 6
  • 85
  • 105
35

Since you now specified you want to add to it, what you want isn't a simple IEnumerable<T> but at least an ICollection<T>. I recommend simply using a List<T> like this:

List<object> myList=new List<object>();
myList.Add(1);
myList.Add(2);
myList.Add(3);

You can use myList everywhere an IEnumerable<object> is expected, since List<object> implements IEnumerable<object>.

(old answer before clarification)

You can't create an instance of IEnumerable<T> since it's a normal interface(It's sometimes possible to specify a default implementation, but that's usually used only with COM).

So what you really want is instantiate a class that implements the interface IEnumerable<T>. The behavior varies depending on which class you choose.

For an empty sequence use:

IEnumerable<object> e0=Enumerable.Empty<object>();

For an non empty enumerable you can use some collection that implements IEnumerable<T>. Common choices are the array T[], List<T> or if you want immutability ReadOnlyCollection<T>.

IEnumerable<object> e1=new object[]{1,2,3};
IEnumerable<object> e2=new List<object>(){1,2,3};
IEnumerable<object> e3=new ReadOnlyCollection(new object[]{1,2,3});

Another common way to implement IEnumerable<T> is the iterator feature introduced in C# 3:

IEnumerable<object> MyIterator()
{
  yield return 1;
  yield return 2;
  yield return 3;
}

IEnumerable<object> e4=MyIterator();
CodesInChaos
  • 106,488
  • 23
  • 218
  • 262
31

No you can't since IEnumerable is an interface.

You should be able to create an empty instance of most non-interface types which implement IEnumerable, e.g.:-

IEnumerable<object> a = new object[] { };

or

IEnumerable<object> a = new List<object>();
Adam Ralph
  • 29,453
  • 4
  • 60
  • 67
  • @AdamRalph: I downvoted, and then got distracted, so couldn't leave a comment immediately. Interfaces are types, so your answer is dangerously wrong because it propagates a common misconception. – jason Jan 05 '11 at 16:27
11

No, You cannot do that. Use the following line of code instead:

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

I hope it helps.

4

The main reason is we can't create object of an interface, and IEnumerable is an interface. We need to create object of the class which implements the interface. This is the main reason we can't directly create object of IEnumerable.

Pawan
  • 167
  • 12
4

You can do this:

IEnumerable<object> list = new List<object>(){1, 4, 5}.AsEnumerable();
CallFunction(list);
Chris Catignani
  • 5,040
  • 16
  • 42
  • 49
N Djel Okoye
  • 950
  • 12
  • 10
1

I wanted to create a new enumerable object or list and be able to add to it.

This comment changes everything. You can't add to a generic IEnumerable<T>. If you want to stay with the interfaces in System.Collections.Generic, you need to use a class that implements ICollection<T> like List<T>.

jason
  • 236,483
  • 35
  • 423
  • 525
0

No IEnumerable is an interface, you can't create instance of interface

you can do something like this

IEnumerable<object> a = new object[0];
Arsen Mkrtchyan
  • 49,896
  • 32
  • 148
  • 184
  • Is it possible to create instance of COM interface like that @Jon Skeet? – Arsen Mkrtchyan Jan 05 '11 at 16:27
  • Absolutely. Weird, but true. See http://stackoverflow.com/questions/1093536/how-does-the-c-compiler-detect-com-types and http://msmvps.com/blogs/jon_skeet/archive/2009/07/07/faking-com-to-fool-the-c-compiler.aspx – Jon Skeet Jan 05 '11 at 16:32
  • 1
    I think it's possible to specify a default implementation that's instantiated instead of the interface for COM interfaces. – CodesInChaos Jan 05 '11 at 16:33
  • @JonSkeet isn't it more accurate to say that calling `new SomeComInterface()` instantiates the interface's associated "CoClass" rather than instantiating the interface itself? – phoog Feb 09 '12 at 14:53
  • @phoog: That would be accurate - but the important and odd thing is that you can use `new` with an interface in certain situations. – Jon Skeet Feb 09 '12 at 14:55
0

It's a pretty old question, but for the sake of newcomers, this is how we can protect an IEnumerable<T> from a null exception. Another word, to create an empty instance of a variable of type IEnumerable<T>

public IEnumerable<T> MyPropertyName { get; set; } = Enumerable.Empty<T>();

https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.empty?view=net-5.0

Cheers.

AminM
  • 329
  • 1
  • 3
  • 14
0

I have been Implementing IEnumerable of type IEnumerable<T> by this way

IEnumerable<T> MyEnum = new T[]{ /*object of type T*/ };

Example:

var Object = new Book{id = 1,name = "Hello World"};
IEnumerable<Book> MyEnum = new Book[]{ Object };