Extension Methods In C#

Posted on

C# extension methods allow developers to extend the capability of  controls  by providing a method which associates itself with the particular control; and provides functionality not built into that control. We can view extension methods as a kind of decorator or dependency injection depending on your inclination. Even though extension methods have been around a while now I rarely see use of it in the code produced by my colleagues even though it would greatly improve readability.

Lets see how we can go about creating an extension method for a popular UI control in Visual Studio the textbox.

Create a new Visual Studio Win. forms project called demoExtension, to that project add a class and name it extensions.cls.

Rename Form1 -> frmDemo and drag a Textbox and Button control unto the form, rename them txtInput and btnSubmit respectively. Set the btnSubmit.Text property to “Submit”.

Replace the code in extensions.cls with the code below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace demoExtension
    static class extensions
        static public bool IsEmailValid(this TextBox emailTextBox)
            if (emailTextBox.Text.Length > 0)
                if (System.Text.RegularExpressions.Regex.IsMatch(emailTextBox.Text, @"^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$"))
                    return true;
                return false;
            return true;

In the click event for btnSubmit enter code.

private void btnSubmit_Click(object sender, EventArgs e)
     if (txtInput.IsEmailValid())
          txtInput.BackColor = Color.Green;
          txtInput.BackColor = Color.Red;

Run the application and enter a malformed email address then hit the submit button.

Retype the email using correct standard then hit submit.

Have fun coding🙂

4 thoughts on “Extension Methods In C#

    Shawn Mclean (@ShawnRMclean) said:
    September 23, 2012 at 6:05 pm

    eww, winforms 😦

      Romaine Carter said:
      September 23, 2012 at 6:09 pm

      lol Shawn, it can work in whatever environment you want. I know you hate winforms🙂

    Rick said:
    October 10, 2012 at 12:02 am

    Extension methods, are pretty cool to use but working with a team, proper naming conventions are highly important as well, good stuff.

    Rick said:
    October 10, 2012 at 12:04 am

    Hey post some stuff about writing custom event listners

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s