Sunday, August 2, 2009

C# Extension Methods - You don't like my methods? Add yer' own.

Have you ever scoured the methods of the string class looking for that method that know has to be there? I do this all the time. I used to write inline functions to handle this until I got smarter and figured out how to create a seperate class of static "helper" methods. This made coding a little easier but now in the .Net 3.5 and .Net 4.0 Framework the new Extension methods have hit the scene. Now, when you're scouring intellisense for that perfect string method and you don't find it, just add it yourself and without subclassing!

Extension methods are static methods that are called as if they were public members of the original class. In other words, your extension method will show up in Intellisense.

namespace ExtensionMethods
{
public static class MyExtensions
{
public static bool WordSaysDog(this String str)
{
If (str == "dog"){
return true;
}
else{
return false;
}
}
}
}

To use this method, simply call it...
string s = "Dog";
bool isDog = s.WordSaysDog();

No comments:

Post a Comment