What is the Extension Method in C#?

Read full article on Infragistics blog

I often get questions about the Extension Method in C#. The Extension Method was introduced in C# Version 3.0. and allows us to add functionalities in an existing class without modifying it, extending it, or re-compiling it.

Essentially, the Extension Method allows us to add a new method to an existing class:

  • · Without modifying it or adding code
  • · Without extending it or creating a new derived type
  • · Without recompiling the class

image

Extension methods are a special kind of static method but can be called on objects like an instance method. So, an extension method can be used in the same way as normal instance methods.

Steps to create an Extension Method

Step 1: Define a static visible class which will contain the Extension Method or Extension Methods. Make sure the class is visible to the client code by applying the appropriate accede modifier.

Step 2: Create a static method with at least the same visibility level as the containing class.

Step 3: The first parameter of the Extension Method always specifies the type method operates on. Make sure the type name is preceded with the “this” modifier.

Step 4: In the calling code, add the namespace that contains Extension Method class.

Step 5: Use the Extension Method on the type in the same instance method can be used. Keep in mind that we do not need to pass the first parameter because that denotes the type, however we should pass the second parameter onwards to call the extension method.

Read full article on Infragistics blog

Published by

Dhananjay Kumar

Dhananjay Kumar is Developer Evangelist for Infragistics. He is a 8 times Microsoft MVP and well respected Developer Advocate in India.He is the author of 900+ Blog Posts, and can often be found speaking around India at conferences and hosting free workshops for programmers across the country. So far, he has hosted 60 free workshops on various topics like JavaScript, Angular, WCF, ASP.NET MVC, C#, Azure etc. Follow him on twitter @debug_mode for all the updates about his blog posts and workshops. You can send him email at debugmode [at] outlook [dot] com

4 thoughts on “What is the Extension Method in C#?”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s