1

Why does the compiler let this expression to compile while the run-time exception is inevitable?

I don't think that the Dynamic Binding should work for void methods

static void Main(string[] args)
{
    var res = Test((dynamic)"test");  // throws RuntimeBinderException exception at runtime
}

static void Test(dynamic args)
{
}

If the C# spec is referring the above expression as dynamically bound expression why doesn't the following method compile?

static dynamic DynamicMethod()
{
}
Kamyar Nazeri
  • 25,786
  • 15
  • 50
  • 87
  • 4
    Basically, when you throw `dynamic` into the pool any sort of compile time checking goes out the window. that's the whole point. – Servy Dec 12 '12 at 17:58
  • so why does the second method throws compile-time exception? – Kamyar Nazeri Dec 12 '12 at 17:59
  • In the second case you know it's not returning anything, there's nothing that could possibly change at runtime to make it return something. In the first case, there could be some other method it doesn't know about (yet) which would allow that to compile and run. – Servy Dec 12 '12 at 18:00
  • Yes, you are right about the second method, but the first one just doesn't make sense, because the compiler should already know that it's not returning anything, neither in compile time nor in the runtime! – Kamyar Nazeri Dec 12 '12 at 18:04
  • 2
    False. It doesn't even know what method it's going to call until runtime, so it couldn't possibly know whether or not a method it hasn't picked does or doesn't have a return value. – Servy Dec 12 '12 at 18:05
  • Thank you Servy, I guess it makes sense now – Kamyar Nazeri Dec 12 '12 at 18:10

1 Answers1

3

Test((dynamic)"abc") is evaluated in its entirety as a dynamic statement. More completely, you could have:

public static string Test(string s) { return s; }

This would be a better overload, so would be selected and executed in preference to the other method.

Or in other words: it can't know whether the return is void without resolving the method-group to a particular signature. And overload resolution is by definition deferred until runtime for a dynamic invoke.

Could it do more analysis? Probably. But the specification does not require it to, so at the absolute most it could be a warning (not an error).

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900