[c#] Initializing IEnumerable<string> In C#

I have this object :

IEnumerable<string> m_oEnum = null;

and I'd like to initialize it. Tried with

IEnumerable<string> m_oEnum = new IEnumerable<string>() { "1", "2", "3"};

but it say "IEnumerable doesnt contain a method for add string. Any idea? Thanks

This question is related to c# .net

The answer is


As string[] implements IEnumerable

IEnumerable<string> m_oEnum = new string[] {"1","2","3"}

IEnumerable is an interface, instead of looking for how to create an interface instance, create an implementation that matches the interface: create a list or an array.

IEnumerable<string> myStrings = new [] { "first item", "second item" };
IEnumerable<string> myStrings = new List<string> { "first item", "second item" };

You can create a static method that will return desired IEnumerable like this :

public static IEnumerable<T> CreateEnumerable<T>(params T[] values) =>
    values;
//And then use it
IEnumerable<string> myStrings = CreateEnumerable("first item", "second item");//etc..

Alternatively just do :

IEnumerable<string> myStrings = new []{ "first item", "second item"};

IEnumerable is just an interface and so can't be instantiated directly.

You need to create a concrete class (like a List)

IEnumerable<string> m_oEnum = new List<string>() { "1", "2", "3" };

you can then pass this to anything expecting an IEnumerable.


You cannot instantiate an interface - you must provide a concrete implementation of IEnumerable.


IEnumerable<T> is an interface. You need to initiate with a concrete type (that implements IEnumerable<T>). Example:

IEnumerable<string> m_oEnum = new List<string>() { "1", "2", "3"};

public static IEnumerable<string> GetData()
{
    yield return "1";
    yield return "2";
    yield return "3";
}

IEnumerable<string> m_oEnum = GetData();