using System; class Runner { static void Main() { A a = new A(); // how to say a.PrintStuff() without a 'using' Console.Read(); } } class A { } namespace ExtensionMethod { static class AExtensions { public static void PrintStuff(this A a) { Console.WriteLine("text"); } } }
How would I call the extension method without a 'using'? And not ExtensionMethod.AExtensions.PrintStuff(a), since that doesn't make use of 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.
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.
Through the use of extension methods a lot of cases can be handled. As extension methods are in reality static methods of another class, they work even if the reference is null . This can be utilized to write utility methods for various cases.
An extension method must be a static method. An extension method must be inside a static class -- the class can have any name. The parameter in an extension method should always have the "this" keyword preceding the type on which the method needs to be called.
It is possible to directly call your extension like so since it is simply a static method, passing the instance it will act on as the first this
parameter:
A a = new A(); ExtensionMethod.AExtensions.PrintStuff(a);
This might be confusing to other developers who happen across this code if you followed this pattern for more commonly used extension methods. It would also make chaining extension calls such as LINQ appear more like a functional language because you would be nesting each call instead of chaining them.
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