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

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...