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 🙂