Arrays as IEnumerable<> instances C# with Example



Arrays as IEnumerable<> instances C# with Example

All arrays implement the non-generic IList interface (and hence non-generic ICollection and IEnumerable base 
interfaces). 
More importantly, one-dimensional arrays implement the IList<> and IReadOnlyList<> generic interfaces (and 
their base interfaces) for the type of data that they contain. This means that they can be treated as generic 
enumerable types and passed in to a variety of methods without needing to first convert them to a non-array form. 
int[] arr1 = { 3, 5, 7 }; 
IEnumerable enumerableIntegers = arr1; //Allowed  because  arrays  implement  IEnumerable 
List listOfIntegers = new List(); 
listOfIntegers.AddRange(arr1); //You can pass in a reference to an array to populate a List. 
After running this code, the list listOfIntegers will contain a List containing the values 3, 5, and 7. 
The IEnumerable<> support means arrays can be queried with LINQ, for example arr1.Select(i => 10 * i). 

0 Comment's

Comment Form

Submit Comment