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…