C#: Dynamic and Extension Methods

What does the following program do?

namespace DynamicExtensionMethods
{
    internal static class Program
    {
        private static int Square(this int i)
        {
            return i * i;
        }

        private static void Main()
        {
            ((dynamic)1).Square();
        }
    }
}

Answer: It crashes.

Unhandled Exception: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'int' does not contain a definition for 'Square'

Apparently, RuntimeBinder doesn’t take extension methods into account. On one hand, it’s surprising because the dynamic binder supposedly acts like the C# compiler’s binder. On the other, RuntimeBinder is a framework thing and extension methods are a language feature. This makes me wonder if there would be any problematic corner cases with supporting extension methods in dynamic method calls…

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s