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;
        }
    }

}
If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

Leave a Reply


x

Interesting BlogPosts to read

How to get an Enumerator from range of elements from ArrayList in C# ?
The code snippet shown in this blog post demonstrates how you can get the enumeraor from a range of ...
How to check for the column name in an SqlDataReader Object in C# ?
When working in ADO.NET for data access , there are times when you want to check to see if a column ...
How to convert Array to List in C#?
Want to convert array of strings to List of strings in C# ? . Below is a sample code to illustrate t...