How to Add Methods to an existing types in C# using Extension Methods ?

The extension methods in C# provides one of the easiest way to add a method to an existing type . Assume that you wanted to add a method for a class for which you don’t have the access to the source code or change the source code . This is where the extension methods come in handy.

How to Add Methods to an existing types in C# using Extension Methods ?

For example , assume that we need to add the method to the string class called IsItGinktage which returns true if the string is “Ginktage” . Below is a code snippet demonstrating this.

Note that the extension methods must be defined in a static class and the extension methods should also be static . The first parameter should be used with the this keyword and with the type for which the extension method is created for .(Eg : string in the below example)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GinktageConsoleApps
{
    class Program
    {
        static void Main(string[] args)
        {
            string Value = "Ginktage";
            Console.WriteLine(Value.IsItGinktage());
            Console.ReadLine();
        }
    }

    public static class Helper
    {
        public static bool IsItGinktage(this string input)
        {
            if (input == "Ginktage")
                return true;
            else
                return false;
        }
    }

}

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

This C# program calculates and displays an upper triangular matrix based on user input. Problem Statement: The program takes the...
This C# program serves as a demonstration of bitwise operators, which are fundamental operators used for manipulating individual bits in...
This C# program is designed to interchange or swap the columns of a matrix. A matrix is a two-dimensional array...