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.
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.
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>
.