C# Programming/Extension methods

Extension methods are a feature new to C# 3.0 and allow you to extend existing types with your own methods. While they are static, they are used as if they are normal methods of the class being extended. Thus, new functionality can be added to an existing class without a need to change or recompile the class itself. However, since they are not directly part of the class, extensions cannot access private or protected methods, properties, or fields.

Extension methods should be created inside a static class. They themselves should be static and should contain at least one parameter, the first preceded by the this keyword:

public static class MyExtensions
{
    public static string[] ToStringArray<T>(this List<T> list)
    {
        string[] array = new string[list.Count];

        for (int i = 0; i < list.Count; i++)
            array[i] = list[i].ToString();

        return array;
    }

    // to be continued...
}

The type of the first parameter (in this case List<T>) specifies the type with which the extension method will be available. You can now call the extension method like this:

List<int> list = new List<int>();

list.Add(1);
list.Add(2);
list.Add(3);

string[] strArray = list.ToStringArray(); // strArray will now contain "1", "2" and "3".

Here is the rest of the program:

using System;
using System.Collections.Generic;

public static class MyExtensions
{
    ... // continued from above

    public static void WriteToConsole(this string str)
    {
        Console.WriteLine(str);
    }

    public static string Repeat(this string str, int times)
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();

        for (int i = 0; i < times; i++)
            sb.Append(str);

        return sb.ToString();
    }
}

class ExtensionMethodsDemo
{
    static void Main()
    {
        List<int> myList = new List<int>();
        
        for (int i = 1; i <= 10; i++)
            myList.Add(i);
        
        string[] myStringArray = myList.ToStringArray();
        
        foreach (string s in myStringArray)
            s.Repeat(4).WriteToConsole(); // string is extended by WriteToConsole()
        
        Console.ReadKey();
    }
}

Note that extension methods can take parameters simply by defining more than one parameter without the this keyword.