Extension Methods In C#

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#

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

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s