What is Extension Methods in c#


Extension methods are new fetures in c# 3.0 which adds the ability to any developer to add extended functionality on any type. Lets say I want to have a new method on a string object, where string object belongs to Microsoft. Without extension methods it is not possible.

Extension methods are new feature added in C# 3.0
These are static methods which can be added by anyone who is even don’t own the object.
To create an extension method on a type, you don’t need to create a derived type of it.

Extension methods can be created only as static and it can be placed only inside a static class.
These methods can be called on the instance of that type.
First argument of this method will be 'this' keyword
Second will be the type on which it is going to execute.

Example,




using System;

public partial class _Default : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

Response.Write ("1231231234".ToPhoneNumber());

}


}

public static class ExtensionMethods

{

public static string ToPhoneNumber(this string word)

{

word = String.Format("({0}) {1}-{2}",

word.Substring(0, 3),

word.Substring(3, 3),

word.Substring(6));

return word;

}

}



The output of this method will be (123) 123-1234


Comments

Author: Pritom Nandy17 Aug 2011 Member Level: Gold   Points : 0

A very good post indeed. Thanks for sharing this concept.

Author: Mohanakrishnan22 Aug 2011 Member Level: Gold   Points : 0

Nice example



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: