What Is an Extension Method In C#? (with an example)

In simpler words, extension method in C# lets you extend the functionality of an existing types (including custom types) to fulfill the requirement without creating a new derived type.

Lets mark few important points about extension methods in c# and jump into the example.

  • To create an extension method first of all you have to create an static method in an static class.
  • The first argument of the static method is the type that you want to extend.
  • The first parameter must be started with “this” keyword.

Getting started with an extension method is very simple even if you are a newbie developer. Let me make it clear with the very simple example.

If you examine the code above, the int ‘i’ has few prebuilt methods that comes along with the c#.

Now I want to extend the int type to fulfill by custom requirement. So lets create an extension method for integer type.

Now I am able to create my own method that can be available to use with the integer type.

You can extend other complex types as well and implement your logic inside that for your requirement.

As I already mentioned on the first statement, you can also extend the custom types. So lets see an example for that.

The extension method can have more then one argument. This is the very beginning introduction article about extension method in C#. You can find lots of article about extension method and the purpose and benefit of using it.

Happy Programming. 🙂

Tagged

About dipneupane

Dip is a passionate Software Developer based in Kathmandu, Nepal. He chew code and smash keyboard for living. Apart from that, he writes about almost everything on buzzedcode.com.

View all posts by dipneupane →

Leave a Reply

Your email address will not be published. Required fields are marked *