by skeet via Jon Skeet: Coding Blog on 6/17/2009 8:01:13 PM
There have been mutterings about the fact that I haven't been blogging much recently. I've been getting down to serious work on the second edition of C# in Depth, and it's taking a lot of my time. However, I thought I'd share a ghastly little example I've just come up with.
I've been having an email discussion with Sam Ng, Chris Burrows and Eric Lippert about how dynamic typing works. Sam mentioned that even for dynamically bound calls, type inference can fail at compile time. This can only happen for type parameters where none of the dynamic values contribute to the type inference. For example, this fails to compile:
Whatever the value of guid is at execution time, this can't possibly manage to infer a valid type argument for T. The only type which can be inferred is string, and that's not a value type. Fair enough... but what about this one?
guid
T
string
I expected the first call to compile (but fail at execution time) and the second and third calls to fail at compile time. After all, T couldn't be both an int and a bool could it? And then I remembered implicit typing... what if the vaue of guid isn't actually a Guid, but some struct which has an implicit conversion from int, bool and string? In other words, what if the full code actually looked like this:
int
bool
Guid
Then T=Foo is a perfectly valid inference. So yes, it all compiles - and the C# binders even get it all right at execution time. So much for any intuition I might have about dynamic typing and inference...
T=Foo
No doubt I'll have similar posts about new C# 4 features occasionally... but they're more likely to be explanations of misunderstandings than deep insights into a correct view of the language. Those end up in the book instead :)
Original Post: Dynamic type inference and surprising possibilities
The content of the postings is owned by the respective author. CSharpFeeds is not responsible for the contents of the postings. This site is automatically generated and cannot be reviewed for abusive content. If you find abusive content on CSharpFeeds, please contact us. Designated trademarks and brands are the property of their respective owners. All rights reserved.