Page 1 of 1

How to create Extension Methods Adding extended methods to existing base classes!!

#1 Byrdsong  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 6
  • View blog
  • Posts: 194
  • Joined: 16-November 08

Post icon  Posted 18 December 2008 - 04:22 PM

Hello All,

Ever wish you had an easier way of doing validation on a string value, or checking to make sure it was in the proper format, or return a value with a simple "ToSomething" other than the defaults that already exists?

For example:
string myEmailAddress; //simple string, nothing fancy
myEmailAddress = "joeATjoe.com";

//now use the extended method to validate the email address
if (myEmailAddress.IsValidEmail())
{
  //email joe something
}
else
{
  //tell the user this email is invalid!!!
}

//how bout this one for my old old old VB buddies that saw the light and crossed over to C#
string myDate;  //still just a string
myDate = "12/18/08" // this could be passed from a user as well...

//now valid using another cool time saving extended method
if (myDate.IsDate()) //OMG where did that come from!!
{
  //do something with it
}
else
{
  //tell em it not a valid date!!
}



Well Extension Methods allow you to do just that and makes them accessible anywhere throughout your project using base class references.

Here's how you create an extended method...

First add a new class to your project

Create a namespace that you MUST make reference to in order to use the extension.
namespace CustomExtensions

Then change the class so that it is static, extension methods only work if they are static (because all base class methods are...)
public static class ExtensionMethods

Now lets add the example extensions mentioned above...
namespace CustomExtensions
{
  public static class ExtensionMethods
  {
	public static bool IsValidEmail(this String str)
	{
			if (!String.IsNullOrEmpty(str.Trim()))
			{
				System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex("^([0-9a-zA-Z]([-.\\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\\w]*[0-9a-zA-Z]\\.)+[com|org|net]{2,3})$");

				if (!regex.Match(str).Success)
					return false;
			}
			else
				return false;

			return true;
  }

  public static bool IsDate(this String str)
  {
			if (!String.IsNullOrEmpty(str.Trim()))
			{
				DateTime chkDate;

				if (!DateTime.TryParse(str, out chkDate))
					return false;
			}
			else
				return false;

			return true;
  }

}



You'll notice the parameter in the method call looks a lil different. With extension methods the first parameter has to be referenced to what base class you are trying to extend. (this String str). The "str" variable simply holds the current state of the object for use of its base methods.

Now on any form/web page you want to use the extension, you MUST make reference to it, "using CustomExtensions" in order to take advantage of it. Try not to name any of your extensions the same as current base class methods or else if will not be read (just the base method).

Because in the examples above I used the String base class, any object that has a .text, .tostring, .value. SelectedText can all have the IsDate() or IsValidEmail() called. It's pretty cool. I have a ton of em!!!

So hopefully this small yet powerfull tutorial help you start thinking about some cool extension methods to add to your projects. Let us know!!

Is This A Good Question/Topic? 1
  • +

Replies To: How to create Extension Methods

#2 prabh  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 3
  • View blog
  • Posts: 381
  • Joined: 27-December 08

Posted 15 February 2009 - 10:40 PM

can some here help me with md5 hash
Was This Post Helpful? 0
  • +
  • -

#3 Guest_Guest*


Reputation:

Posted 02 April 2010 - 11:52 AM

Very good article -------- keep it up
Was This Post Helpful? 0

#4 KewlBeans  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 15
  • Joined: 12-December 09

Posted 16 April 2010 - 10:17 PM

I <3 extensions!!1

I know they do the same thing as any static method, but they make the code so pretty!
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1