Extension Methods In C#

Introduction

Extension methods are static methods that are always implemented in a static class.

They don’t need a class object; they can be directly called. In C#, we already have some built-in extension methods like Union, Where and Zip. These extension methods need a System—Linq namespace declaration.

extension methods

In C#,  Extension methods can be identified by this logo. Extension methods can be defined in C# in a separate .cs file.

The extension method is called an instance method but is actually a static method. The instance pointer "this" is a parameter, and you must specify the "this" keyword before the appropriate parameter you want the method to be called upon.

The difference between a regular static method and an extension method is that, in a static method, we first provide the class name and then we call the method. In the extension method, the "this" keyword is in the parameter list. You can directly call this by a variable.

Create an Extension method.

  1. Open Visual Studio
  2. "File" ">>" New >> "Web Site..."
  3. Select "ASP.NET Empty Web Site", then click "OK"
  4. Add a new WebForm
  5. Add a new Class

ExtentionMethods.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
/// Summary description for ExtensionMethods
/// </summary>
public static class ExtensionMethods
{
    public static string UpperCaseFirstLetter(this string value)
    {
        if (!string.IsNullOrEmpty(value))
        {
            string[] words = value.Split(' ');
            value = string.Empty;
            foreach (string word in words)
            {
                char[] getWord = word.ToCharArray();
                getWord[0] = char.ToUpper(getWord[0]);
                value += new string(getWord) + " ";
            }
            value = value.Trim();
        }
        return value;
    }
}
string getValue = new string(getWord);

if (string.IsNullOrEmpty(value))
{
    value = getValue;
}
else
{
    value = value + ' ' + getValue;
}
}
}
return value;
}
}

In the code above, you can see we have a public static class, ExtentionMetods. In this class, there is a method "public static string UpperCaseFirstLetter(this string value)" in which the value is obtained, and then this function converts the first letter to uppercase.

Call Extention method in C# program

Default. aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            Name <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
        </div>
        <div>
            <asp:Button ID="Button1" runat="server" Text="Call Extension Method" OnClick="Button1_Click" />
        </div>
    </form>
</body>
</html>

Default. aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // Code for Page_Load event (if any)
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        // Check if txtName is not empty
        if (!string.IsNullOrEmpty(txtName.Text))
        {
            // Get the text from txtName
            string name = txtName.Text;
            // Call the UpperCaseFirstLetter extension method and set the text to txtName
            txtName.Text = name.UpperCaseFirstLetter();
        }
    }
}

Look at the code above; we have a text box, txtName, and a Button. When the user enters text into the TextBox and clicks on the button, it executes the click event code, and we have a name variable that is a string type.

Look at this line.

// Call the UpperCaseFirstLetter extension method on the 'name' variable
// and assign the result to the Text property of the 'txtName' TextBox.
txtName.Text = name.UpperCaseFirstLetter();

Here we call our UpperCaseFirstLetter extention method in the name variable. You remember our method parameter was defined like this, the string value. That’s why when you use a name variable, it comes directly into the Intellisense.

C# extension method

That’s it; press F5 and run your code.


Recommended Free Ebook
Similar Articles