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

Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s