Extension methods in C#

Extension methods in C#

In this article describe the concept of extension method in c#. Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Here we describe the uses of extension methods and simple example of extension methods n c#.

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type.

Extension methods are defined as static methods but are called by using instance method syntax. Their first parameter specifies which type the method operates on, and the parameter is preceded by the ‘this’ modifier. Extension methods are only in scope when you explicitly import the namespace into your source code with a using directive.

Advantages of extension methods

·Extension methods allow existing classes to be extended without relying on inheritance or having to change the class's source code.

·If the class is sealed than there in no concept of extending its functionality. For this a new concept is introduced, in other words extension methods.

·This feature is important for all developers, especially if you would like to use the dynamism of the C# enhancements in your class's design.

Disadvantages of extension methods

·An extension method with the same name and signature as an instance method will not be called.

·Extension methods cannot be used to override existing methods.

·The concept of extension methods cannot be applied to fields, properties or events.

Syntax for creating extension methods

static class <class_name>

{

static <return type> <method name> (this extension_class object)

{

// definition

}

}

Here we create the extension method using the ‘this’ keyword and it refer to the class which extension method create.