Extension methods in C#

Wikipedia has a very good overview of extension methods in C# here.

Basically, if you create a static method in a static class and the first parameter includes the keyword ‘this’ then the first parameter will be the calling object and you’ve created an extension method.

Here is a quick example console application (based on the example from Wikipedia):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("abcdefg".ExtReverse());
            Console.ReadLine();
        }
    }

    public static class ExampleExtension
    {
        public static string ExtReverse(this string input)
        {
            char[] chars = input.ToCharArray();
            Array.Reverse(chars);
            return new String(chars);
        }
    }
}

Leave a Reply

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