Understand Extension Methods in C# within 10 minutes

Understand Extension Methods in C# within 10 minutes

·

4 min read

According to MSDN , Extension Methods enable you to add methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.

Extension methods are special kinds of static method, but they are called as if they were instance methods on the extended type.

In C# every class has different built in methods peculiar to the class, this means its impossible to call a method outside the instance of the class. This limitation is mitigated using Extension Methods, with extension methods, you can create custom methods for operation you intend to carry out and this has no effect on the performance of the running program. Lets understand Extension methods using the following Examples.

using System.Linq;
using System.Collections.Generic;
using System;
namespace ExtensionMethods
{
    class Program
    {
        static void Main(string[] args)
        {
            string number = "123456789;
            string result = number.GetFirstIndexOfNumber(); // Compiler Error (No such method exist for the type)
            Console.WriteLine(result);
        }
    }
}

Looking at the code snippet above you would have a compile error, as number which is an instance of the string class does not contain the GetFirstIndexOfNumber method. To add this functionality to the string class then you would need what is called an Extention Method.

Create a class called ExtensionHelper

namespace ExtensionMethods
{
    public static class ExtensionHelper
    {
        public static string GetFirstIndexOfNumber(this string number)
        {
            if(number.Length > 0) {
                char [] charArray = number.ToCharArray();
                var result = charArray[0];
                return result.ToString();
            }
            return number;
        }
    }
}

The convention for naming Extension methods are they are to be defined as static.

  • Create a static method GetFirstIndexOfNumber with a string return type.
  • Then pass in a string argument with a this keyword in front of it.
  • An if condition checks whether the length of the number is greater than 0 else it returns the number.
  • if the condition is satisfied the number is converted into a character array, charArray.
  • Afterwards the first index of the character array is selected, charArray[0], this is then converted back to a string and returned.

With the following helper extension method, number can now call the GetFirstIndexOfNumber without a compile error.

string result = number.GetFirstIndexOfNumber();

This line of code above is referred to as syntactic sugar as its is then converted to

string result = HelperExtension.GetFirstIndexOfNumber(number);

before its executed.