Search code examples
c#c#-4.0language-design.net-4.0

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?


Solution

  • 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.