Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call an extension method without using

Tags:

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.

like image 610
countunique Avatar asked Jul 24 '13 03:07

countunique


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 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.

Can you call extension method on null?

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.

Do extension methods have to be static?

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.


1 Answers

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.

like image 113
AaronLS Avatar answered Oct 23 '22 14:10

AaronLS