Extension Methods in C# - An Introduction with Examples and Output

3 minute read

Introduction

Extension methods are a powerful feature in C# that allows developers to add new functionality to existing classes without modifying the original source code. This article will provide an introduction to extension methods, along with some examples and output to demonstrate how they work.

What are Extension Methods?

An extension method is a static method that is used to extend the functionality of an existing class without modifying the original class definition. Extension methods are defined in a static class and must be marked with the “this” keyword before the first parameter. This tells the compiler that the method is an extension method and can be called as if it were a member of the extended class.

Extension methods are typically used to add functionality to classes that cannot be modified directly, such as classes in the .NET Framework. They are also useful for creating reusable code that can be shared across multiple projects.

Example of Extension Method

Here’s an example of how to create an extension method that adds a new method to the String class:

public static class StringExtensions
{
    public static bool IsNullOrEmpty(this string value)
    {
        return string.IsNullOrEmpty(value);
    }
}

In this example, the “IsNullOrEmpty” method is added to the String class as an extension method. The method checks whether the string is null or empty and returns a boolean value.

To use the extension method, simply call it as if it were a member of the String class:

string str = null;
bool result = str.IsNullOrEmpty();

In this example, the “IsNullOrEmpty” method is called on a null string. Because it is an extension method, it can be called even though the String class does not have a method with this name.

Output of the Extension Method Example

The output of the above code will be “true”, since the string “str” is null and the “IsNullOrEmpty” method returns true for null strings.

Here’s another example that demonstrates how to create an extension method that calculates the sum of an array of integers:

public static class IntExtensions
{
    public static int Sum(this int[] values)
    {
        int sum = 0;
        foreach (int value in values)
        {
            sum += value;
        }
        return sum;
    }
}

To use the extension method, simply call it as if it were a member of the int array:

```csharp
int[] values = { 1, 2, 3, 4, 5 };
int sum = values.Sum();

In this example, the “Sum” method is called on an int array. Because it is an extension method, it can be called even though the int class does not have a method with this name.

Output of the Extension Method Example

The output of the above code will be “15”, since the “Sum” method calculates the sum of the values in the array.

Another Example


using System;

namespace ExtensionMethodsExample
{
    public static class MathExtensions
    {
        public static double RoundTo(this double number, int decimalPlaces)
        {
            double multiplier = Math.Pow(10, decimalPlaces);
            return Math.Round(number * multiplier) / multiplier;
        }

        public static int Factorial(this int number)
        {
            if (number == 0 || number == 1)
            {
                return 1;
            }
            else
            {
                return number * Factorial(number - 1);
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            double pi = 3.141592653589793;
            double roundedPi = pi.RoundTo(4);
            Console.WriteLine($"Pi rounded to 4 decimal places: {roundedPi}");

            int num = 5;
            int factorial = num.Factorial();
            Console.WriteLine($"Factorial of {num}: {factorial}");
        }
    }
}

In this example, we have created a static class called “MathExtensions” that contains two extension methods: “RoundTo” and “Factorial”.

The “RoundTo” method takes a double number and an integer number of decimal places, and returns the number rounded to the specified number of decimal places.

The “Factorial” method takes an integer number and calculates its factorial.

In the Main method, we have created a double variable “pi” and called the “RoundTo” method on it to round it to 4 decimal places. We have also created an integer variable “num” and called the “Factorial” method on it to calculate its factorial.

The output of this code will be:

Pi rounded to 4 decimal places: 3.1416
Factorial of 5: 120

This advanced example demonstrates how extension methods can be used to add complex functionality to existing classes, such as calculating the factorial of an integer or rounding a double to a specified number of decimal places.

Conclusion

Extension methods are a powerful feature in C# that allow developers to add new functionality to existing classes without modifying the original source code. They are defined in a static class and must be marked with the “this” keyword before the first parameter. Extension methods are typically used to add functionality to classes that cannot be modified directly, such as classes in the .NET Framework. They are also useful for creating reusable code that can be shared across multiple projects.

Tags:

Categories:

Updated: