Extension Method in C#

In C#, the extension method concept allows you to add new methods in the existing class or in the structure without modifying the source code of the original type and you do not require any kind of special permission from the original type and there is no need to re-compile the original type. It is introduced in C# 3.0.

C# extension method is a static method of a static class, where the "this" modifier is applied to the first parameter. The type of the first parameter will be the type that is extended. When you use Visual Studio Intellisense, you can see the extension method is represented with an arrow (different from the normal method sign), since they were instance methods on the extended type. See the figure below : 



Extension methods, as the name suggests, are additional methods. Extension methods allow you to inject additional methods without modifying, deriving or recompiling the original class, struct or interface. Extension methods can be added to your own custom class, .NET framework classes, or third party classes or interfaces.

IsGreaterThan() is an extension method for int type, which returns true if the value of the int variable is greater than the supplied integer parameter.


An extension method must be defined in a top-level static class.

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.

Overuse of extension methods is not a good style of programming.


Advantages:

The main advantage of the extension method is to add new methods in the existing class without using inheritance.

You can add new methods in the existing class without modifying the source code of the existing class.

It can also work with sealed class.

No comments:

Post a Comment