C# Language Arrays Arrays as IEnumerable<> instances

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

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<int> enumerableIntegers = arr1; //Allowed because arrays implement IEnumerable<T>
List<int> listOfIntegers = new List<int>();
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<int> containing the values 3, 5, and 7.

The IEnumerable<> support means arrays can be queried with LINQ, for example arr1.Select(i => 10 * i).



Got any C# Language Question?