Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't the c# compiler check "staticness" of the method at call sites with a dynamic argument?

Tags:

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"?

like image 506
Rune Avatar asked Nov 12 '11 16:11

Rune


1 Answers

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.

like image 166
Hans Passant Avatar answered Sep 27 '22 22:09

Hans Passant