Now we will focus on extension methods. As the name indicates, extension methods is the mechanism to add (or extend) methods to existing types without having to inherit or recompile the assembly/project where the type resides.
Extension methods must comply with the following:
- They are declared as static methods
- The first parameter specifies which type the method operates on
- The first parameter is preceded by the this modifier
- Declared in a non-generic, non-nested static class
Although extension methods are declared as static methods, they are called as instance methods on the extended type.
The following is a declaration of a class that contains an extension method for the int type. The method Add, adds a value to any given integer and the resulting value is returned.
In the example, we can validate that we covered all the requisites for extension methods. Please pay special attention to the first parameter in the method, which contains the this modifier; this will allow us to call the static method, by an instance of the int type as we can see in the following calls:
The first call uses the 10 (as an instance of the int type) and adds to it 20. The resulting value is returned by the method and assigned to the extendedAddition1 variable. Then this variable (another instance of the int type) is used to call the Add method for a second time. The resulting output is as follows.