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();