MOZ
MOZ

Reputation: 758

Foreach loop to get an IEnumerable<T>

When using a foreach loop to loop through a collection of values types, is it necessary to get an IEnumerable<T> interface instead of a non-generic IEnumerable interface, to prevent the unwanted intermediate luggage instructions unbox to appear in your compiled code?

Upvotes: 2

Views: 118

Answers (2)

Richard
Richard

Reputation: 108975

is it necessary

It certainly is not necessary (necessary in this context means required).

Is it a good idea: yes. Saving unboxing in most cases will be a micro-optimisation (except in the inner loops of CPU limited data processing). But if you know you have a collection of some type of value type then keeping that information does not waste time on a box-unbox cycle and makes the code easier to work with.

The last point, given IDE's intellisense like capabilities, is by far the most valuable.

Upvotes: 5

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149538

There is no reason to implement the non-generic IEnumerable nowadays, yourself. There are cases where you'll be forced to use it, for example in collections that rely on the old IEnumerable implementation, where you have no control.

It is mainly there for backwards-compatibility to the date before generics came to the framework (.NET 1.0). When you want to implement an iterator, use IEnumerable<T>, always.

Upvotes: 2

Related Questions