Why don't dynamic objects and extension methods play nice?

60 views Asked by At

The causes of the exception:

Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax.

Have been covered in several SO questions (here and here ).But no one has said why the Framework doesn't allow this:


Example

public static class ExampleExtension
{
    public static string HelloWorld(this object o, object o2)
    {
        return "Hello World";
    }

    public static void Test()
    {
        dynamic dynamicObject = new object();

        //Exception
        new object().HelloWorld(dynamicObject);

        //No Exception
        ExampleExtension.HelloWorld(new object(), dynamicObject);
    }
}

new object().HelloWorld(dynamicObject)` is bad


ExampleExtension.HelloWorld(new object(), dynamicObject)` is good


Why?

If extension methods are essentially just syntactic sugar for calling a static method, wouldn't new object().HelloWolrd() be converted to the compiler to ExampleExtension.HelloWorld(new object()) anyway? So why can't the DLR handle this?

0

There are 0 answers