DEV Community

mohamed Tayel
mohamed Tayel

Posted on

C# Advanced:Extension Methods

In many cases, you may not have the luxury of owning or modifying the codebase you’re working with, and subclassing might not be an option. This is where extension methods come in handy, allowing you to add functionality to existing types without modifying their original structure. They are particularly useful for creating reusable code that can be shared across projects.


What are Extension Methods?

An extension method allows you to add new methods to an existing type without changing the original code. It’s like adding a method to a class, but you define it externally in a static class.

Let’s look at some examples to make this clearer.


A Simple Example: Extending string

Suppose you want to add a method to check if the first letter of a string is capitalized. You can’t modify the string class directly, but you can create an extension method.

public static class StringExtensions
{
    public static bool IsCapitalized(this string str)
    {
        if (string.IsNullOrEmpty(str)) return false;
        return char.IsUpper(str[0]);
    }
}
Enter fullscreen mode Exit fullscreen mode

Now, you can use this method like it’s part of the string class:

string name = "John";
bool result = name.IsCapitalized();  // Returns true
Enter fullscreen mode Exit fullscreen mode

Extending Custom Classes: Order Example

Let’s say you have an Order class, and you want to add a method to calculate an estimated delivery date:

public class Order
{
    public DateTime OrderDate { get; set; }
}

public static class OrderExtensions
{
    public static DateTime GetDeliveryDate(this Order order, int deliveryDays)
    {
        return order.OrderDate.AddDays(deliveryDays);
    }
}
Enter fullscreen mode Exit fullscreen mode

You can now call this method like it’s part of the Order class:

Order myOrder = new Order { OrderDate = DateTime.Now };
DateTime deliveryDate = myOrder.GetDeliveryDate(5);  // Adds 5 days to the order date
Enter fullscreen mode Exit fullscreen mode

Extending Interfaces: IOrder Example

You can also extend interfaces. Suppose you have an IOrder interface that several classes implement, and you want to add a method to calculate discounts:

public interface IOrder
{
    decimal TotalPrice { get; }
}

public static class OrderExtensions
{
    public static decimal ApplyDiscount(this IOrder order, decimal discountPercentage)
    {
        return order.TotalPrice - (order.TotalPrice * discountPercentage / 100);
    }
}
Enter fullscreen mode Exit fullscreen mode

You can now use this method on any class that implements IOrder:

public class OnlineOrder : IOrder
{
    public decimal TotalPrice { get; set; }
}

IOrder order = new OnlineOrder { TotalPrice = 100 };
decimal discountedPrice = order.ApplyDiscount(10);  // Returns 90
Enter fullscreen mode Exit fullscreen mode

Assignments

Here are some assignments to practice creating and using extension methods, categorized by difficulty.

Easy: Extending int

Task: Create an extension method for the int type that checks if a number is even.

Steps:

  1. Define a static class.
  2. Add a static method IsEven that takes an int as a parameter.
  3. Use the this keyword to extend the int type.

Hint: Use the modulo operator (%) to check if a number is even.

int number = 4;
bool isEven = number.IsEven();  // Should return true
Enter fullscreen mode Exit fullscreen mode

Medium: Extending a Custom Class

Task: Create an extension method for a Person class that calculates the person's age based on their date of birth.

Steps:

  1. Define a Person class with a DateOfBirth property.
  2. Create a static class PersonExtensions.
  3. Add a method GetAge to calculate the age based on DateTime.Now.

Hint: Use DateTime.Now and DateTime.Year to calculate the difference between the current year and the year of birth.

public class Person
{
    public DateTime DateOfBirth { get; set; }
}

Person person = new Person { DateOfBirth = new DateTime(1990, 5, 24) };
int age = person.GetAge();  // Should return the person's age
Enter fullscreen mode Exit fullscreen mode

Difficult: Extending a Collection

Task: Create an extension method for List<int> that returns only the prime numbers from the list.

Steps:

  1. Define a static class ListExtensions.
  2. Add a method GetPrimes that filters out non-prime numbers.
  3. Use a helper method to check if each number is prime.

Hint: A number is prime if it’s only divisible by 1 and itself.

List<int> numbers = new List<int> { 2, 3, 4, 5, 6, 7, 8 };
List<int> primes = numbers.GetPrimes();  // Should return { 2, 3, 5, 7 }
Enter fullscreen mode Exit fullscreen mode

Conclusion

Extension methods are a powerful feature in C# that allow you to add new functionality to existing types without modifying their original code. They provide a clean, reusable, and maintainable way to extend classes and interfaces, making them a great tool in any developer’s toolkit.

By completing the assignments above, you will gain practical experience in using extension methods, from simple types like int to more complex scenarios like filtering collections.

Top comments (0)