0

Is it possible to overwrite instance methods by an extension-methods? For example, I have an assembly (compiled, without sources) and I want to rewrite some behaviour.

I created some code for test:

public class SomeClass
{
    public void MyMethod()
    {
        Console.WriteLine("Instance method is called");
    }
}

public static class ExtMethods
{
    public static void MyMethod(this SomeClass c)
    {
        Console.WriteLine("Extention method is called");
    }
}

then I try to use:

SomeClass s = new SomeClass();
s.MyMethod();

It's compiled successfully, IntelliSence marks this method as instance (extension method has another icon)

enter image description here

output says

Instance method is called

none note about extention method exists. So, no way to overwrite instance method, right?

Why the behavior of the compiler and VS is such non-informative? If I develop an extension-method and there exists already the same instance method (and I don't know about it), I can spend hours to understand why behavior is different than expected...

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
Oleg Sh
  • 8,496
  • 17
  • 89
  • 159
  • How non-informative? https://msdn.microsoft.com/en-us/library/bb383977.aspx explains everything. In the section "Binding Extension Methods at Compile Time" it actually answers your exact question. – Willem van Rumpt Feb 26 '15 at 12:29

1 Answers1

3

No, you cannot override the instance method with extension methods. Hence, the name 'extension' method, you can only extend the instance methods.

An instance method will always override the extension method.

If you want to force to call the extension method, call it as a regular static method:

ExtMethods.MyMethod(yourClassInstance);

About the why VS doesn't tell you it is a duplicate: actually it can't do that. What if you have an extension method on object. Should VS check all classes and their methods if any method is a duplicate? They simply didn't build the check, it is something you should do yourself.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325