Extension Methods In C#

What is Extension Method,

  1. Extension method feature is introduced in C# 3.0.
  2. Extension of a method is a way to add some more methods, as per the requirement into an existing library.
  3. For example, in the string, we have the methods like length(), split(), substring() etc. If we want that we should have one more method that will count number of words in a string we can extends string methods by adding one more method WordCount().

Properties of Extension Methods

  1. It is a static method.
  2. It must be in a static class.
  3. It uses "this" keyword as a first parameter with a type in .NET.

Sum of digits of a number can be calculated, using an extension method.

Step 1. We will create an extension method.

code

The method, shown above, takes an integer number as an input and calculate the sum of its digit and returns the sum of the digits of the number.

Step 2. Now, we are going to call this method from the code, like other inbuilt methods.

code

We have created an extension method for int numbers and we have seen, it can be call like other inbuilt methods.

Example Flow

code

Next Recommended Reading Extension methods in C# 3.0