How to create an extension method in C#

Extension methods are methods that add additional functionality to any C# type without creating a new derived type or modifying the original type.

Format of Extension methods in C

public static class NameOfTheClass
{
    public static ReturnType(this typeOfTheSource source)
    {
        // Extension method definition
    }
}

Example: Extension Method

.NET provides a static method that indicates whether a specified string is null oe an empty string. We can take this functionallity and wrap it in a custom extension method.

public static class StringExtensions
{
    public static bool IsNullOrEmpty(this string source)
    {
        return string.IsNullOrEmpty(source);
    }
}

Usage

string str = "just a string";
if (str.IsNullOrEmpty())
{
    // do something if the string is null or empty
}

Example: Extension method with additional parameters

The following example demostrates how to generate extension method with additional parameters. The bellow method rounds a given decimal to the given precission.

public static class DecimalExtensions
{
    public static decimal Rounding(this decimal dec, int precision)
    {
        return Math.Round(dec, precision);
    }
}

Example: Generic extension methods

The following extension method take generic value types as parameters and source. This method searches if a given value exists in a given array.

public static class StructExtensions
{
    public static bool In<T>(this T value, params T[] parms) where T : struct
        => parms.Any(x => x.Equals(value));
}