C#: Extension Methods

One cool feature that I found useful in C# are the so called Extension Methods. So what are Extension Methods you say ? Extension methods are in simple terms allows you to extend an existing type with additional functionality without having to modify the the old type.

Let’s say you have a program that have a series of methods related to string manipulations. So the common thing to do is to put all your string manipulation methods in a single class which we can call MyUtilities class:

MyUtilities

Then here is a sample snippet in using the MyUtilities class:

MainProgram

We are expecting the results to be:

Watch

Applying the concept of Extension Methods you can easily integrate your string related manipulations to the string type itself without modifying it.

Here is a sample snippet for MyExtensionMethods class:

MyExtensionMethods

Using the MyExtensionMethods in the MainProgram:

MainProgramExtensionMethod.PNG

Still we get the same results from our previous example using the MyUtilities class:

Watch

Things to keep in mind while using Extension Methods, It would be a good practice to store it in a separate source file such as MyExtensionMethods.cs.

Extension Method class should be declared as static class with a public access modifier so that it  can easily be consumed.

Another thing to keep in mind is that every Extension Methods should contain the keyword this in order for the compiler to distinguish it as an Extension Method.

HAPPY CODING 🙂

Advertisements

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