Tuesday, December 8, 2009

Extension method on the string object

I am going to show you how to create an extension method on the string object to validate if that string is a valid guid.
To make this simple, we'll create a new console application, add a class and name it Extensions or any name you want, I usually stick with some naming conventions so Extensions is pretty descriptive.
Now, we need to make that class public and static for this to work. The code is very simple..see below:


public static class Extensions
{
public static bool IsValidGuid(this string g)
{
try
{
Guid gd = new Guid(g);
return true;
}
catch (Exception)
{
return false;
}
}
}
Notice that we used the keyword "This" to let it know that this is going to be an extended method.
To use the method, we just make the call directy on the string we have ..example:
string s = "some text or guid string!"
Console.writeline(s.IsValidGuid());
And that all there is to it. Now you have an extention method ready to go.