CatalinRadoi
6/9/2015 - 5:53 PM

C# extension methods

C# extension methods

using System;

internal class Program
{
    private static void Main(string[] args)
    {
        string s = "This is a test";

        Console.WriteLine("Word count: {0}" ,s.WordCount());
        Console.WriteLine(s.Concatenate(" baby"));
        Console.ReadLine();
    }
}
using System.Linq;

public static class MyAwesomeExtensions
{
    public static int WordCount(this string input)
    {
        return input.Split(' ').Count();
    }


    public static string Concatenate(this string input, string toAdd)
    {
        return input + toAdd;
    }

    public static bool IsNullOrEmpty(this string s)
    {
        return string.IsNullOrEmpty(s);
    }
}

Extension Method = static method of a static class that can be invoked by using the instance method syntax.

The first parameter of the function, the one with the "this" keyword, specifies what type are you extending.

More on Extension Methods - MSDN