C# Extension Methods

Updated on     Kisan Patel

Extension methods allow an existing type to be extended with new methods, without altering the definition of the original type.

An extension method is a static method of a static class, where the this modifier is applied to the first parameter.

The type of the first parameter will be the type that is extended.

For example,

public static class StringUtils
{
	static public double ToDouble(this string data)
	{
		double result = double.Parse(data);
		return result;
	}
}

The ToDouble extension method can be called as differently as shown below.

string text = "40.54";
Console.WriteLine(text.ToDouble());

Let’s take one example to understand how extension method work.

using System;
using System.Linq;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            string zipCode = "382840";
            string email = "pka246@gmail.com";
            Console.WriteLine("Email is valid : " + StringHelpers.IsValidEmail(email));
            Console.WriteLine("ZipCode is valid (called extension method) : " + zipCode.IsValidPostalCode());
        }
    }

    public static class StringHelpers
    {
        //This is a extension method
        public static bool IsValidPostalCode(this string value)
        {
            return value.Length == 6 || value.Length == 6;
        }

        //This is not a extension method
        public static bool IsValidEmail(string value)
        {
            return value.Contains('@');
        }
    }
}

The output of the above C# program…

linq-extension-methods-demo

System.Linq defines extension methods for IEnumerable and IQueryable.

There are over 50 Standard query operators like Select, OrderBy, Where and many more.


C# LINQ

Leave a Reply