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()
{
}
6
  • 4
    Basically, when you throw dynamic into the pool any sort of compile time checking goes out the window. that's the whole point. Commented Dec 12, 2012 at 17:58
  • so why does the second method throws compile-time exception? Commented Dec 12, 2012 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. Commented Dec 12, 2012 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! Commented Dec 12, 2012 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. Commented Dec 12, 2012 at 18:05

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.