this.Blog.Find(entry => entry.IsHelpful);
 Wednesday, May 14, 2008
C# Extension Methods

In my last post, I showed an example of how you can create an extension method on an existing class in javascript.  Well, C# 3.0 has now added the exact same functionality.  And it just so happens that today I needed to create one, so I thought I would post an example of how it's done in C#.

public static class StringExtensions 
{
public static byte[] ToByteArray(this string s)
{
return ASCIIEncoding.UTF8.GetBytes(s);
}
}

Extension methods act like static methods on existing classes, and as such they can only be declared in static classes. To mark a method as an extension method, you must preface the declaration of the first parameter in the method signature with the keyword "this". The compiler will then add the method to the type of class declared in the first parameter. Any other parameters declared after the first one will become the signature to the extension method.

Now we can call the extension method we added to the String class:

public class Program 
{
public static void Main(string[] args)
{
string myString = "Foo";
byte[] bytes = myString.ToByteArray();
}
}

The other cool thing is that Visual Studio provides full Intellisense on all extension methods!  So in the example I provided, ToByteArray() is now offered up as a potential method anytime I reference a string.


Kick it on DotNetKicks.com
Wednesday, May 14, 2008 12:43:26 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  .Net | C#

Comments are closed.