Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do arrays in .net only implement IEnumerable and not IEnumerable<T>?

I was implementing my own ArrayList class and was left surprised when I realised that

public System.Collections.Generic.IEnumerator<T> GetEnumerator() {     return _array.GetEnumerator(); } 

didn't work. What is the reason arrays don't implement IEnumerator in .NET?

Is there any work-around?

Thanks

like image 738
devoured elysium Avatar asked May 05 '10 13:05

devoured elysium


People also ask

Does array implement IEnumerable in C#?

All arrays implement IList, and IEnumerable. You can use the foreach statement to iterate through an array.

Why is IEnumerable used in C#?

IEnumerable is an interface defining a single method GetEnumerator() that returns an IEnumerator interface. It is the base interface for all non-generic collections that can be enumerated. This works for read-only access to a collection that implements that IEnumerable can be used with a foreach statement.

What is IEnumerable T?

IEnumerable<T> is the base interface for collections in the System. Collections. Generic namespace such as List<T>, Dictionary<TKey,TValue>, and Stack<T> and other generic collections such as ObservableCollection<T> and ConcurrentStack<T>.

Is IEnumerable faster than List C#?

IEnumerable is conceptually faster than List because of the deferred execution. Deferred execution makes IEnumerable faster because it only gets the data when needed. Contrary to Lists having the data in-memory all the time.


1 Answers

Arrays do implement IEnumerable<T>, but it is done as part of the special knowledge the CLI has for arrays. This works as if it were an explicit implementation (but isn't: it is done at runtime). Many tools will not show this implementation, this is described in the Remarks section of the Array class overview.

You could add a cast:

return ((IEnumerable<T>)_array).GetEnumerator(); 

Note, older MSDN (pre docs.microsoft.com) coverage of this changed a few times with different .NET versions, check for the remarks section.

like image 82
Richard Avatar answered Sep 25 '22 01:09

Richard