main banner


Methods in .NET - Extension methods (Part 3)

Previously, we have explained named and optional arguments (part 1) and parameters with variable number of arguments (part 2).

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. 

Methods in .NET

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:

Methods in .NET

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.

Methods in .NET

Osvaldo G.

Calling Osvaldo “el Doc” is no coincidence, he is part of the Inflection Point’s gurus and has been working in the company for 9 years; his degree in Computer Engineering, the numerous certifications and more than 15 years of experience in Microsoft technologies, have made of him a mentor for many and also an avid writer for Inflection Point’s blog with tips and facts that have saved more than one coder in their quest for better coding. He comes from San Nicolás de los Garza, Nuevo Leon and is a Tigres (local soccer team) fan.