Initializing IEnumerable<string> In C#

C#.Net

C# Problem Overview


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

C# Solutions


Solution 1 - C#

Ok, adding to the answers stated you might be also looking for

IEnumerable<string> m_oEnum = Enumerable.Empty<string>();

or

IEnumerable<string> m_oEnum = new string[]{};

Solution 2 - C#

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"};

Solution 3 - C#

As string[] implements IEnumerable

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

Solution 4 - C#

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.

Solution 5 - C#

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

IEnumerable<string> m_oEnum = GetData();

Solution 6 - C#

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

Solution 7 - C#

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"};

Solution 8 - C#

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" };

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmarkzzzView Question on Stackoverflow
Solution 1 - C#seheView Answer on Stackoverflow
Solution 2 - C#BasView Answer on Stackoverflow
Solution 3 - C#Bob ValeView Answer on Stackoverflow
Solution 4 - C#ChrisFView Answer on Stackoverflow
Solution 5 - C#Kirill PolishchukView Answer on Stackoverflow
Solution 6 - C#BonyTView Answer on Stackoverflow
Solution 7 - C#yan yankelevichView Answer on Stackoverflow
Solution 8 - C#Alexander OhView Answer on Stackoverflow