Reputation: 1798
Many people ask me why, and I don`t have a good answer for them.
Obviously there is a good reason. Does anyone know it?
I searched here and found this question. It explains how it works, but not why.
Upvotes: 2
Views: 530
Reputation: 81307
There are a couple more advantages to duck-typed foreach versus IEnumerable:
The second advantage can really only be achieved via duck-typing.
Upvotes: 1
Reputation: 1503599
Suppose you wanted the equivalent of an IEnumerable<int>
but were using C# 1.0. You could implement IEnumerable
- but that would require boxing and unboxing on each iteration. Using the sort of duck-typing version of foreach
you could get away without any boxing. In many cases the boxing wouldn't actually be that harmful (I tend to find that the performance hit is exaggerated) but it's still inelegant.
I strongly, strongly suspect that if generics had been around in C# 1.0, foreach
would have been restricted to IEnumerable<T>
.
Upvotes: 11