Extension Methods in c#
Posted On: 05-Apr-2016 00:10
Extension methods enable us to "add" methods to existing types (like int, String, etc) 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. There is no apparent difference between calling an extension method or the methods that are actually defined in a type code written in C# or VB.NET. In this article we will try to create an extension method on existing type 'String' that will count word in the type.
Most Common Extension Methods
The most common extension methods are the LINQ standard query operators that add query functionality to the existing System.Collections.IEnumerable and System.Collections.Generic.IEnumerable<T> types.
How to Use
First bring them into scope with a using System.Linq directive (importing package). Then any type that implements IEnumerable<T> appears to have instance methods such as OrderBy, GroupBy, Average, and so on. You can see these additional methods in IntelliSense statement completion when you type . (dot) after an instance of an IEnumerable<T> type such as List<T> or Array.
Some Feature of Extension Methods
The following are basic features and properties of extension methods that we going to create:
- It is a static method.
- It must be in a static class.
- It uses the "this" keyword as the first parameter with a type in .NET(C#,VB).
- It also shown by VS intellisense. When we press the . (dot) after a type instance, then it comes in VS intellisense.
- An extension method should be in the same namespace as it is used or you need to import the namespace of the class by a using statement.
- The static class can have any name.
- If the extension methods have the same signature methods as the type you are extending, then the extension methods will never be called.
Here, we going to create a extension method 'WordCount'. It will return the count of the type string.
I) Create a class MyExtension as:
II) Now we have created extension method in step (I) and ready to use it. Now bring it into scope with this using directive as:
III) Now we can call the WordCount extension method as:
IV) Run the Code It will return 5.
In this article we create an extension method. I hope it will help us to create own extension methods.