4

While trying to write elegant answer to another SO question I stumbled upon strange issue on extension methods.

Consider the following setup:

public class Foo
{
}

public static class Extensions
{
    public static string ExtensionTest(this object o)
    {
        return "object overload called";
    }

    public static string ExtensionTest(this Foo f)
    {
        return "Foo overload called";
    }
}

When I execute following:

object o = new Foo();
Console.WriteLine(o.ExtensionTest());

It outputs object overload called (instead of Foo overload called)

  1. Why not dynamic binding?
  2. Is there any way to "force" dynamic binding on extension methods (without messy if-elses or switching types)?
Risto M
  • 2,919
  • 1
  • 14
  • 27
  • 3
    Extensions are static methods by definition. – Renat Apr 17 '19 at 18:45
  • 1
    These problems tend to come up when we don't make full use of strong typing. In most cases we can write or modify our code to work with more specific types and avoid casting things as `object`. – Scott Hannen Apr 17 '19 at 18:52
  • ah ok.. Extension method is just syntax sugar which seems like instance method. `Console.WriteLine(o.ExtensionTest())` is actually this: `Console.WriteLine(Extensions.ExtensionTest(o))` I've wrote those for years but didn't think about it deep enough.. – Risto M Apr 17 '19 at 18:58
  • 2
    Extension methods are a compiler implemented feature. "Why not dynamic binding?" - for that I can think of several reasons, the least of which would be potential method name conflicts between loaded assemblies that define their own _ExtensionTest_ method. – TnTinMn Apr 17 '19 at 19:00
  • @TnTinMn You are right, those `Dynamic binding failed due to name conflict` exceptions would not be nice to get at run-time.. – Risto M Apr 17 '19 at 19:14
  • 1
    Is there a way to force dynamic binding? Sure, it's just not useful because it won't work with extension methods: `Console.WriteLine(Extensions.ExtensionTest((dynamic) o));` Resolving extension methods is purely a compile-time exercise. There are [good reasons for that](https://stackoverflow.com/a/5313149/4137916). – Jeroen Mostert Apr 18 '19 at 09:20

0 Answers0