Initializing IEnumerable <string> In C #

I have this object:

IEnumerable<string> m_oEnum = null; 

and I would like to initialize it. I tried

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

but he says: β€œIEnumerable does not contain a method to add a string. Any idea? Thanks

+76
c #
Jul 04 2018-11-14T00:
source share
6 answers

Well, by adding to the answers you can also search

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

or

 IEnumerable<string> m_oEnum = new string[]{}; 
+124
Jul 04 2018-11-14T00:
source share

IEnumerable<T> is the interface. You need to start with a specific type (which implements IEnumerable<T> ). Example:

 IEnumerable<string> m_oEnum = new List<string>() { "1", "2", "3"}; 
+69
Jul 04 2018-11-11T00:
source share

How string[] implements IEnumerable

 IEnumerable<string> m_oEnum = new string[] {"1","2","3"} 
+21
Jul 04 2018-11-11T00:
source share

IEnumerable is just an interface and therefore cannot be directly created.

You need to create a specific class (e.g. List )

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

you can pass this on to anything IEnumerable expects.

+14
Jul 04 2018-11-11T00:
source share
 public static IEnumerable<string> GetData() { yield return "1"; yield return "2"; yield return "3"; } IEnumerable<string> m_oEnum = GetData(); 
+8
Jul 04 2018-11-11T00:
source share

You cannot instantiate an interface β€” you must provide a concrete implementation of IEnumerable.

+4
Jul 04 2018-11-11T00:
source share



All Articles