Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why dynamic call return dynamic result?

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?

like image 504
dotneter Avatar asked Oct 22 '10 13:10

dotneter


2 Answers

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.

like image 123
Justin Niessner Avatar answered Nov 12 '22 05:11

Justin Niessner


This blog posting might be helpful to you: Link

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.

like image 27
Tim Goodman Avatar answered Nov 12 '22 05:11

Tim Goodman