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]);
}
}
Now, you can use this method like it’s part of the string
class:
string name = "John";
bool result = name.IsCapitalized(); // Returns true
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);
}
}
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
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);
}
}
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
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:
- Define a static class.
- Add a static method
IsEven
that takes anint
as a parameter. - Use the
this
keyword to extend theint
type.
Hint: Use the modulo operator (%
) to check if a number is even.
int number = 4;
bool isEven = number.IsEven(); // Should return true
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:
- Define a
Person
class with aDateOfBirth
property. - Create a static class
PersonExtensions
. - Add a method
GetAge
to calculate the age based onDateTime.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
Difficult: Extending a Collection
Task: Create an extension method for List<int>
that returns only the prime numbers from the list.
Steps:
- Define a static class
ListExtensions
. - Add a method
GetPrimes
that filters out non-prime numbers. - 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 }
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)