5/2/2008 5:49:10 PM
Another "Late Pass" series entry. I've just recently started using extension methods and seeing how useful they can be. Extension methods have been pretty fun to write so far. It's nice to find yourself wanting a piece of functionality and then having the power to now do it.
My first extension method deals with Guids. I tend to use Guids a lot and there is no real way to convert something to a Guid. Let's say you have a QueryString value that is a unique identifier (i.e. Guid) and you want to check for it, convert it to a Guid, then do something with it (i.e. retrieve employee information, etc...) I've found that to do this I'd need to some variation of the following:
string
s = Request.QueryString["Guid"];
Guid guid == Guid.Empty;
if (!string.IsNullOrEmpty(s))
try
{
guid = new Guid(s);
}
catch (FormatException)
{
guid = Guid.Empty;
}
if (guid != Guid.Empty)
{
// do stuff with Guid g
}
Enter my first extension method: IsGuid(). This provides a less verbose method of doing business.
if (s.IsGuid())
{
Guid guid = new Guid(s);
// do stuff with guid
}
There is another option:
Guid guid = Request.QueryString["Guid"].ConvertToGuid();
if (guid != Guid.Empty)
{
// do stuff with Guid
}
Here is the code for the extension methods. First you will you need a RegularExpression for the format of the Guid. That's easy enough as Guids have the same format 8-4-4-4-12 (would provide a link to where I found this regular expression but I forgot where I got it 8^( )
private
static readonly Regex _guidRegex = new Regex(@"^(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}$", RegexOptions.Compiled);
Now the actual methods:
public
static bool IsGuid(this string value)
{
return !string.IsNullOrEmpty(value) ?
_guidRegex.IsMatch(value) : false;
}
public static Guid ConvertToGuid(this string value)
{
return string.IsNullOrEmpty(value) ? Guid.Empty :
(_guidRegex.IsMatch(value) ? new Guid(value) : Guid.Empty);
}
Again, I apologize for the line breaks. I need to implement a new CSS layout. By implement I mean find a free one that isn't a complete mess.
I'll be posting more extension methods in the future. Too bad I missed the bus a couple of months ago!
Easy.
.NET,
C#,
Code
