Why doesn't the C# compiler tell me that this piece of code is invalid?
class Program { static void Main(string[] args) { dynamic d = 1; MyMethod(d); } public void MyMethod(int i) { Console.WriteLine("int"); } }
The call to MyMethod
fails at runtime because I am trying to call a non-static method from a static method. That is very reasonable, but why doesn't the compiler consider this an error at compile time?
The following will not compile
class Program { static void Main(string[] args) { dynamic d = 1; MyMethod(d); } }
so despite the dynamic dispatch, the compiler does check that MyMethod
exists. Why doesn't it verify the "staticness"?
Overload resolution is dynamic here. Visible in this code snippet:
class Program { public static void Main() { dynamic d = 1.0; MyMethod(d); } public void MyMethod(int i) { Console.WriteLine("int"); } public static void MyMethod(double d) { Console.WriteLine("double"); } }
Works fine. Now assign 1 to d and note the runtime failure. The compiler cannot reasonably emulate dynamic overload resolution at compile time, so it doesn't try.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With