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