Extension Methods (Simple example in C# language)

Monday, May 18, 2020

Hi Friends,

After a long time I am writing something on this blog. As you can see that my first priority is to deliver my thought on very simple way which will help you to clear the concept. Today we will understand that what is the basic use of Extension Methods and how we create them. 

Extension methods are used to add methods in existing classes (a custom class or framework class) without changing them or inheriting them as a new class. Extension method need to be static and class in which you define extension method should also be an static class.

For example in order to convert string into integer I don't want to use Convert.ToInt32() method as it is not much handy for a programmer. So, I need to create my own method which can be used in any string variable and it looks like the method is available in existing "string" class provided by .net framework. I will create a new static class named "Extension" then create an static method in it named ToInt() which will be used in any string type to convert its value into integer type.

I am using IDE - Microsoft Visual Studio 2019.

1. Open Visual Studio.
2. File > New > Project.
3. Create New Project by selecting "Visual C#"  and selecting "Console App (.Net Framework) and click "OK" button.

New Project


4. Add a new class by right clicking on project > Add > Class.




5. Name it anything for example "Extension" and click "Add" button.

Extension class

6. Extension class should be static. 
7. Add following method in this class:

public static int ToInt(this string Value)
{
  int.TryParse(Value, out int result);
  return result;
}

it will look like this: (note that the class should be static).

Extension class with code

8. Then add following code into Main() method of Program class:

string stringYear = "2020";
Console.WriteLine(stringYear.GetType() + " - " + stringYear);

int intYear = stringYear.ToInt();
Console.WriteLine(intYear.GetType() + " - " + intYear);
Console.Read();

It will look like this:

Program class with code


9. Press F5 to execute the program, you will see the following output:



Which shows that the code is working fine and now with the help of extension method, you can use our newly created ToInt() method by just pressing "." dot after any string variable.

There are a lot more complex examples than this but this was the simplest example by which I can demonstrate you the basic use of extension methods. 

Please feel free to ask anything regarding this on my provided contact details.

**************************LINKS******************************

I have created a new better blog:

My Youtube channel:

**************************LINKS******************************

Thanks
Have a nice day!