How To Use .NET 3.5 "Extension Methods" for Validation
(
Sep 19 2007 - 07:38:03 AM by
Timothy Khouri) - [
print blog
post]
The new language feature (Extension Methods) brought to C# and VB.NET in Visual Studio 2008 (.NET framework 3.5) is a great tool to speed up validation routines. At first I didn't think that this feature would really be used a lot, but I'm really loving it.
Obviously, the benefits that come with extension methods for the purpose of LINQ are great, but here's something that I have long wished I could do in the past, and now I can thanks to extension methods!
if (this.PhoneNumberTextbox.Text.IsPhoneNumber() == false)
{
}
Or how about this:
if (this.BidPriceTextBox.Text.IsDecimal() == false)
{
}
Now, you could say that I could just use a RegularExpressionValidator (which I could) to accomplish those above functions. But, when inserting the item into a database, I can also do this:
DataAccessLayer.UpdateBidPrice(this.BidPriceTextBox.Text.ReturnAsDecimal());
How to Make an Extension Method
It's really easy to make your own extension methods. Basically, you just make a public static method on ANY CLASS in your project and you make the first parameter be the type that you want to "extend" (which in my examples above I'm extending the "string" type). Also, you need to add the "this" keyword. Here's how to make my "ReturnAsDecimal" method above:
public static decimal ReturnAsDecimal(this string input)
{
decimal result;
return (decimal.TryParse(input, out result)) ? result : 0;
}