Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call extension method which has the same name as an existing method? [duplicate]

I have code like

public class TestA {     public string ColA { get; set; }     public string ColB { get; set; }     public string ColC { get; set; }     public void MethodA()     {         MessageBox.Show("Original A1.");     } }  static class ExtenstionTest {        public static void MethodA(this TestA A1)     {         MessageBox.Show("Extended A1.");     } } 

Now if I call MethodA like

TestA a = new TestA();         a.MethodA(); 

It will always call Original method. How can I call the extension method.

like image 284
D J Avatar asked Nov 23 '12 06:11

D J


People also ask

How do you call an extension method?

To define and call the extension methodDefine a static class to contain the extension method. The class must be visible to client code. For more information about accessibility rules, see Access Modifiers. Implement the extension method as a static method with at least the same visibility as the containing class.

Can you add extension methods to an existing static class?

No. Extension methods require an instance of an object.

Can we call a method from an extension on dynamic types?

We can not call the Extension method on the dynamic type.

Can we override extension method?

You can use extension methods to extend a class or interface, but not to override them. An extension method with the same name and signature as an interface or class method will never be called.


2 Answers

You can't call the extension method as a normal extension method. The instance method overrides the extension method with the same signature

EDIT:

You can call it as a static method

ExtensionTest.MethodA(a); 
like image 79
Mihai Avatar answered Sep 29 '22 21:09

Mihai


You can't call it as an extension method. It's basically useless at this point, in terms of being an extension method. (Personally I'd like this to be a warning, but never mind.)

The compiler tries all possible instance methods before it attempts to resolve extension methods. From section 7.6.5.2 of the C# 4 spec:

In a method invocation of one of the forms [...] if the normal processing f the invocation finds no applicable methods, an attempt is made to process the construct as an extension method invociation.

and later:

The preceding rules mean that instance methods take precedence over extension methods

You can call it like a regular static method though:

// Fixed typo in name ExtensionTest.MethodA(a); 
like image 31
Jon Skeet Avatar answered Sep 29 '22 21:09

Jon Skeet