Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I was aware that something remotely similar is done when rewriting LINQ query expressions but I was not aware of this one. My first thought was that they added it to support dynamic and objects not implementing IEnumerable but as you mentioned exactly this seems to be the case where it would not work. I had a look at the C# 1.0 specification and it's already in there but a lot less verbose.

Any idea why they did this? The only thing this seems to achieve is that you can implement IEnumerable and IEnumerator without explicitly stating it. Are there any (common) classes to which this applies?



One big benefit of using structural (rather than nominal) typing in the foreach construct is that value types don't need to be boxed.


I am not sure about this - why would requiring an interface require boxing?


Interfaces are reference types and so if the GetEnumerator method on a struct is called through an interface then it must be boxed.


I see your point but I am not yet convinced. At least if the interface method is not explicitly implemented, I can call the same method not through the interface. But I don't know the specs well enough to judge if this would be a viable optimization avoiding boxing or if this could cause different behavior, for example if you start handing out the this pointer. Thinking a bit more about it, it probably does. Maybe I will have a closer look at this out of curiosity.


Yes, if the method is not explicitly implemented then you can call it without going through the interface.

But at that point it's just a regular method that might also happen to implement part of an interface that you the programmer are not using (at least at that point).

Likewise in the case of foreach, the compiler is looking for a particular method and does not need to care whether or not that method happens to also implement part of an interface, so there is not point in making the programmer go through the trouble of marking the type as such.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: