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.
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.
No. Extension methods require an instance of an object.
We can not call the Extension method on the dynamic type.
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.
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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With