Extension Methods

Introduction

Extension Methods allow user to add additional feature or methods to existing class without creating a new derived type.

Before diving into extension method, lets understand why we use extension method in c#?

Example Suppose that there is a class with n number of methods, and you want to add more methods into it.

you can add Extension methods using below two approach:

  1. You can directly write more methods into it, But the problem is that there might be chance that the class is already tested and adding more methods to the same class will need put extra efforts to re-test the entire class again.
  2. Second choice would be we can inherit the sub class from parent and write extra methods into sub class. In this approach problem is that these methods are of the child class and not the parent class.

Some time we need to add the more methods to the class owned by someone else (Don’t have source code for the same)

Extension method is the saviours from all above conditions, as it is meant for it.

In object-oriented computer programming, an extension method is a method added to an object after the original object was compiled. The modified object is often a class, a prototype or a type

Wiki

Extension method is a mechanism of adding new methods into an existing class or structure without modifying the source code of the original type (a class or a structure) and we also don’t require any permissions from the original type. The original type doesn’t require any recompilation as well as we are not touching the original type. We will see all this in a bit.

Benefits of extension methods

• Extension methods allow existing classes to be extended without relying on inheritance or having to change the class’s source code.
• Extension method is useful to extended sealed class functionality.
• This feature is important for all developers, especially if you would like to use the dynamism of the C# enhancements in your class’s design.

The approach for implementing the extension methods is as follows:

  1. Define a static class – so that all methods inside it is static.
  2. Define your methods inside this static class.
  3. Bind this static class with the existing class or structure.

Example:
Suppose we have parking system, which designed for collection parking fees.

using System;

namespace ParkingSystem
{
    class Program
    {
        static void Main()
        {
            var parking = new Parking();

            if (parking.IsParkingFull())
            {
                Console.WriteLine("Parking is Full");
                return;
            }

            Console.WriteLine("Enter Vehicle Number:");
            var vehicleNumber = Console.ReadLine();

            Console.WriteLine("Enter Vehicle Type:");
            var vehicleType = Convert.ToInt32(Console.ReadLine());

            parking.ParkVehicle(vehicleNumber);
            var fees = vehicleType == 1 ? 
                parking.TwoWheelFees() : 
                parking.FourWheelFees();

            Console.WriteLine($"You vehicle is parked at {parking.ParkVehiclePlace()} number. \nYou need to pay {fees}$");
            Console.ReadLine();
        }
    }
}

Parking class:

namespace ParkingSystem
{
    public class Parking
    {
        public  const int MaxParkingLimit = 100;

        public int CurrentParkingSize;

        public bool IsParkingFull()
        {
            return CurrentParkingSize < MaxParkingLimit;
        }

        public void ParkVehicle(string vehicleNumber)
        {
            CurrentParkingSize++;
            //Update vehicleNumber and vehicle place in to database
        }

        public int ParkVehiclePlace()
        {
            return CurrentParkingSize;
        }

        public int TwoWheelFees()
        {
            return 5;
        }

        public int FourWheelFees()
        {
            return 20;
        }
    }
}

Now in this system we need to add few more methods in parking class to check the parking directions so will use extension method for the same.

using System;

namespace ParkingSystem
{
    static class ParkingExtension
    {
        public static string ParkDirection(this Parking parking)
        {
            return IsEvenDay(DateTime.Now.Day) ? "LeftDirection" : "RightDirection";
        }

        public static bool IsEvenDay(this int day)
        {
            return day / 2 == 0;
        }
    }
}

After adding this extension, we can see this method are also added to the parking class and can see as part of parking class. There is no need to change existing parking class.

Another example is let’s add extension to an existing string class to repeat the string in n number of a time.

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

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

        return sb.ToString();
    }
}

With above example, string class has new extension method which can repeat string with n number of times.

The only thing that separates extension method from static method, is the “this” keyword in the parameter section of the method. It tells the compiler that this is an extension method.

Extension method with Generic Type:

Extension method can be implemented with generic type suppose we have list object which we need to convert into string;

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

The type of the first parameter (in this case List) 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();

FAQ – Interview Question about Extension Method:

  1. Why we need static method to define Extension methods?
    Extension methods are not called in the context of the object on which the method is declared so we are passing instance of other class using “this” keyword and not the instance of a class in which its defined. Hence therefore there is no way to pass them this reference, therefore they must be static.
  2. Why we use “this” keyword in extension method?
    The “this” keyword refers to the current instance of the class. So, to extend functionality of a class by adding a method we need to pass the current instance of the class. Hence, we need “this” keyword.
  3. Why we need static class to define Extension methods?
    First, its design decision. Suppose we have added extension method in non-static class then it would be confusing while creating an instance of define extension methods and instance methods in the same class And also, that will not making any sense hence we need static class to define extension method.

Leave a Reply

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