public string Foo(object obj) {
return null;
}
public string Foo(string str) {
return null;
}
var x = Foo((dynamic) "abc");
Why is x dynamic, compiler not smart enough or I miss something important?
public string Foo(object obj) {
return null;
}
public string Foo(string str) {
return null;
}
var x = Foo((dynamic) "abc");
Why is x dynamic, compiler not smart enough or I miss something important?
I'm just guessing here, but...
When you add a cast to dynamic
, the entire expression becomes a dynamic expression. The result of a dynamic expression is always going to be dynamic
because everything is resolved at run-time.
Check out the MSDN page on using dynamic
for more info:
Using Type dynamic (C# Programming Guide)
And scroll to the following text:
The result of most dynamic operations is itself dynamic.
This blog posting might be helpful to you: http://blogs.msdn.com/b/cburrows/archive/2010/04/01/errata-dynamic-conversions-and-overload-resolution.aspx
In particular: "If you have a method call with a dynamic argument, it is dispatched dynamically, period."
That means C# doesn't know which overload is being called until runtime. It doesn't know at compile time. My understanding is that it doesn't even check what the possible overloads are at compile time (why would it?), or make a note of the fact that in your case they all return strings.
So at compile time, the return value of Foo
isn't known. Thus the type of x
is determined at compile time to be dynamic
.