SingingEels : Development Community & Resource

Login

Articles

  • ADO.NET (2)
  • ASP.NET (35)
  • LINQ (4)
  • Security (2)
  • Silverlight (2)
  • SQL (7)
  • Standards (5)
  • WCF (2)

Syndication

  • Articles RSS
  • Blogs RSS

Contribute

  • Our Authors List
  • Member Sign-Up
  • Suggestions Box
ASP.NET Hosting with MS SQL 2008 – Click Here!

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)
{
   // Display some error message...

}

Or how about this:

if (this.BidPriceTextBox.Text.IsDecimal() == false)
{
   // Display some error message...

}

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;
}

You must be logged in to add comments. If you have not already done so, you can create an account here. If you already are a member, you first need to login before you can comment.

Developer / Architect / Author

Blog Archives

  • November 2008 - (1)
  • October 2008 - (2)
  • September 2008 - (2)
  • August 2008 - (3)
  • July 2008 - (1)
  • June 2008 - (3)
  • May 2008 - (2)
  • April 2008 - (2)
  • March 2008 - (4)
  • February 2008 - (2)
  • December 2007 - (2)
  • November 2007 - (1)
  • October 2007 - (4)
  • September 2007 - (9)
  • August 2007 - (7)

Related Ads

SingingEels.com as of Nov 21 2008 - 08:05:19 PM - (0.0937476)