Extension methods are a introduced in C# 3.0. An extension method enables us to add methods to existing types without creating a new derived type, recompiling, or modify the original types. An extension method is a static method to the existing static class. We call an extension method in the same general way, there is no difference in calling.
Rules for defining an extension method
- The extension method needs to be defined in a nongeneric static class
- The static class must be at the root level of a namespace (that is, not nested within another class)
- The extension method must be a static method (which is enforced by the compiler due to the class also having to be marked static)
- The first argument of the extension method must be prefixed with the this modifier; this is the type being extended
Property of Extension Methods
- It is a static method.
- It must be located in a static class.
- It uses the “this” keyword as the first parameter with a type in .NET and this method will be called by a given type instance on the client side.
- It also shown by 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.
- You can give any name for the class that has an extension method but the class should be static.
- If you want to add new methods to a type and you don’t have the source code for it, then the solution is to use and implement extension methods of that type.
- If you create extension methods that have the same signature methods as the type you are extending, then the extension methods will never be called.
In the above method Increment(), Decrement() and CreateHtmlLink() we are passing a integer type with this so it will be called by the int type variable, in other words a Integer instance.
Now we create a static class and two static methods, one for the decrement by 1 in a int and another for the increment in a int.