views:

233

answers:

1

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.

+7  A: 

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

Jon Skeet
Generics were the BIG MISSING FEATURE ("BMF") of v1.0, a fact which rippled throughout the framework and languages. This is just one example of something that would have been designed differently, and now can't be fixed.
Jay Bazuzi
@Jay: Agreed. There will always be such things, of course - but I would personally rather they'd delayed by .NET 1.0 a year (or more) and put generics in. Big marketing headache. Fortunately of course this *particular* little complexity in C# doesn't actually cause much damage. There are worse :(
Jon Skeet