The Dummies’ Guide to How to solve Problems with Extension Method

I am pretty much sure that, You have used Extension method in your program. Did you think to create your custom Extension method ?

If not then this article help you to create your own Extension method step by step.

Before jumping to direct practice let’s understand first what is extension method. So, an Extension method is created to simplify the code. It is a static method which represent as instance method. It accepts “this” keyword as a parameter.

If you see below example image you are not going to surprise as you have used this type of method.

extension_Method_1-1

Now, let me tell you more about the Extension method. As you now aware it is a static method & it accept “this” as a parameter so just need to add a “.” dot symbol with variable and all the existing method will be appear.

The question come to our mind how to create our own Extension method. So, it is simple and easy. We need to create a static class first and then that static class we can create our own Extension method.

extension_method2-1

Once you added a class in your solution specify the class as a static class and a static method in the class. In below example I am using static method with name  “MyStringCharacterLength”  if you see the below snap you will find in the parameter we are using this which is must for an extension method. We are not doing any fancy with this method it is a simple logic of calculating the length of the string.

Extension_Method_3

Now once the extension method is created we can use this method using by a “.” dot symbol. Isn’t it easy let me show you the code.

extension_Method_4

When we run this code it will return the length of the string which provided as a input.

I hope a basic now you have a basic understanding of extension method. You can create your various method to use this and reduce your efforts in cases where you have to write similar logic again and again.

I recommend below site from where you can download existing Extension method and  use it.

http://extensionmethod.net/

I hope you have a clear view of extension method now.

Enjoy!!

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