Search code examples
c#genericsenumerable

c# generic versus non generic enumerators


A newbie question.

Arrays in C# return a non generic (classic) IEnumerator. Other collections can supply either.

In general, is it bettter use a generic enumerator if it is available, eg for reasons of type safety? Are there times when the non-generic option is preferable?


Solution

  • Usually it's highly preferable to use generic enumerations, for, as you mentioned in question, type safety.

    Non generic enumeration can be a choice in case when you store just a collection of objects. So instead of writing IEnumerable<object>, you write IEnumerable and figure out the real object type inside the iteration (if you need that, but usually yes).