DEV Community

Katherine Mykhailyk
Katherine Mykhailyk

Posted on

C# Extension Methods: the basics you need to know

Image description

Extension methods are a powerful feature (introduced in C# 3.0) in object-oriented programming languages that allow a method to be added to an object, including a class or a type, after it has been compiled.

When creating extension methods, you would typically use static methods within static classes and the “this” modifier. Although extension methods are static, they can be invoked as if they were instance methods. However, extension methods cannot be defined for static classes, and they cannot override methods of a class or interface. If an extension method has the same name and signature as a class or interface method, it will not be called. Additionally, at compile time, instance methods defined in the type itself will always have a higher priority than extension methods.

Extension methods are actually widely used in C# development and is often leveraged indirectly through popular libraries like LINQ, which uses extension methods to add query functionality to existing types such as System.Collections.IEnumerable and System.Collections.Generic.IEnumerable. This allows developers to query collections with great ease and flexibility. For example:

List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
var result = numbers.Where(n => n % 2 == 0).Select(n => n * n);
Enter fullscreen mode Exit fullscreen mode

The following logic is performed behind the scenes (simplified code of Where and Select LINQ methods):

public static class MyLinqExtensions
{
    public static IEnumerable<T> Where<T>(this IEnumerable<T> source, Func<T, bool> predicate)
    {
        foreach (T item in source)
        {
            if (predicate(item))
            {
                yield return item;
            }
        }
    }

    public static IEnumerable<TResult> Select<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector)
    {
        foreach (TSource item in source)
        {
            yield return selector(item);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Extension methods provide a more convenient way of writing code, leading to improved readability and discoverability. For example, consider the following two code snippets:

// Case 1: We don't have extension methods and need to use static methods

var total = Enumerable.Aggregate(
                Enumerable.Distinct(
                    Enumerable.Select(
                        Enumerable.Where(myList, x => x.price > 5)
                       , x.price)
                    )
               , (total, next) => total + next);

// Case 2: We have extension methods

var total = myList.Where(x => x.price > 5)
                  .Select(x => x.price)
                  .Distinct()
                  .Aggregate((total, next) => total + next);
Enter fullscreen mode Exit fullscreen mode

The following extension methods use cases are among the most popular:

1) The most significant benefit of using extension methods is that they provide a convenient means of adding extra features to the .Net Framework or third-party classes that cannot be modified or don’t have access to the source code. For example:

// The UserManager class that is part of the 
// Microsoft.AspNetCore.Identity library has been extended
// by adding a new method called FindByPhoneNumberAsync

public static class UserManagerExtension
{
    public static async Task<AppUser?> FindByPhoneNumberAsync(this UserManager<AppUser> userManager, string? phoneNumber)
    {
        return await userManager.Users.FirstOrDefaultAsync(u => u.PhoneNumber == phoneNumber);
    }
}

// Example of use

var user = await _userManager.FindByPhoneNumberAsync(phoneNumber);
Enter fullscreen mode Exit fullscreen mode

2) Extending the functionalities on a DTO. For example:

// Our DTO

public class TransferDTO
{
  public int Id {get;set;}
  public string Name {get;set;}
}

// Extension method

public static class TransferDTOExtension 
{
    public static int GetName(this TransferDTO transfer) 
    {
        return transfer.Name;
    }
}

// Example of use

var transfer = new TransferDTO();
Console.WriteLine(transfer.GetName()); // Extra functionality!
Enter fullscreen mode Exit fullscreen mode

3) Collection Functionality. This is basically what we have seen higher. They allow the functionality to be called from any collection such as an System.Array or System.Collections.Generic.List that implements System.Collections.Generic.IEnumerable on that type.

In conclusion, extension methods in C# provide a powerful and flexible way to extend existing types without modifying their source code. They enable developers to add new functionality to types, including third-party types or types that are part of the .NET framework. Extension methods also make code more readable by allowing developers to write fluent and concise code. However, it is important to use extension methods judiciously and avoid creating ambiguous or confusing code. When used appropriately, extension methods can be a valuable tool for improving code quality and maintainability in C#.

Top comments (0)