Duck typing in the C# compiler

后端 未结 3 1447
囚心锁ツ
囚心锁ツ 2020-11-27 19:06

Note This is not a question about how to implement or emulate duck typing in C#...

For several years I was under the impression that certai

3条回答
  •  误落风尘
    2020-11-27 19:43

    There's nothing special about IDisposable here - but there is something special about iterators.

    Before C# 2, using this duck type on foreach was the only was you could implement a strongly-typed iterator, and also the only way of iterating over value types without boxing. I suspect that if C# and .NET had had generics to start with, foreach would have required IEnumerable instead, and not had the duck typing.

    Now the compiler uses this sort of duck typing in a couple of other places I can think of:

    • Collection initializers look for a suitable Add overload (as well as the type having to implement IEnumerable, just to show that it really is a collection of some kind); this allows for flexible adding of single items, key/value pairs etc
    • LINQ (Select etc) - this is how LINQ achieves its flexibility, allowing the same query expression format against multiple types, without having to change IEnumerable itself
    • The C# 5 await expressions require GetAwaiter to return an awaiter type which has IsCompleted / OnCompleted / GetResult

    In both cases this makes it easier to add the feature to existing types and interfaces, where the concept didn't exist earlier on.

    Given that IDisposable has been in the framework since the very first version, I don't think there would be any benefit in duck typing the using statement. I know you explicitly tried to discount the reasons for having Dispose without implementing IDisposable from the discussion, but I think it's a crucial point. There need to be good reasons to implement a feature in the language, and I would argue that duck typing is a feature above-and-beyond supporting a known interface. If there's no clear benefit in doing so, it won't end up in the language.

提交回复
热议问题