What Are Extension Methods?
Before diving into extension members, let’s quickly revisit extension methods—a feature introduced in C# 3.0.
Extension methods let you “add” methods to existing types without modifying their source code. For example:
public static class StringHelpers
{
public static bool IsNullOrEmpty(this string value)
{
return string.IsNullOrEmpty(value);
}
}
// Usage
string name = null;
bool result = name.IsNullOrEmpty(); // true
This is especially useful when working with types you don’t own, like string, DateTime, or third-party libraries.
What’s New in C# 14: Extension Members
C# 14 takes this concept further by allowing you to define:
- Extension properties
- Extension indexers
- Static extension members
These members behave like native members of the type, making your code cleaner and more intuitive.
public static class DateTimeExtensions
{
extension(DateTime date)
{
public bool IsWeekend => date.DayOfWeek is DayOfWeek.Saturday or DayOfWeek.Sunday;
}
}
// Usage
DateTime today = DateTime.Now;
Console.WriteLine(today.IsWeekend); // Output: true or false
Example 1: Extension Property for DateTime
Let’s say you’re building a scheduling app and want to check if a date is on a weekend:
public static class DateTimeExtensions
{
extension(DateTime date)
{
public bool IsWeekend => date.DayOfWeek is DayOfWeek.Saturday or DayOfWeek.Sunday;
}
}
// Usage
DateTime today = DateTime.Now;
Console.WriteLine(today.IsWeekend); // Output: true or false
Example 2: Extension Indexer for List
In a reporting tool, you might want to access the first or last item in a list using a string key:
public static class ListExtensions
{
extension<T>(List<T> list)
{
public T this[string key] => key switch
{
"first" => list.First(),
"last" => list.Last(),
_ => throw new ArgumentException("Invalid key")
};
}
}
// Usage
var items = new List<string> { "Apple", "Banana", "Cherry" };
Console.WriteLine(items["first"]); // Output: Apple
Console.WriteLine(items["last"]); // Output: Cherry
Example 3: Static Extension Member for Guid
In a logging system, you might want a shortcut to generate a new GUID:
public static class GuidExtensions
{
extension(Guid)
{
public static Guid New => Guid.NewGuid();
}
}
// Usage
Guid id = Guid.New;
Console.WriteLine(id);
Example 4: Extension Property for Custom Type
Imagine you have a custom Invoice class and want to calculate the total amount:
public class Invoice
{
public decimal Amount { get; set; }
public decimal Tax { get; set; }
}
public static class InvoiceExtensions
{
extension(Invoice invoice)
{
public decimal Total => invoice.Amount + invoice.Tax;
}
}
// Usage
var invoice = new Invoice { Amount = 100, Tax = 25 };
Console.WriteLine(invoice.Total); // Output: 125
How to Create Your Own Extension Members
That looks cool and interesting, right?
Let’s dive in and see how you can create your own custom extension members in C# 14. Whether you're enhancing built-in types or extending your own classes, the process is simple and powerful.
Here’s how to do it:
- Create a static class to hold your extensions.
- Use the extension(Type) syntax to define members.
- Access them just like native members.
public static class MyExtensions
{
extension(string s)
{
public int VowelCount => s.Count(c => "aeiouAEIOU".Contains(c));
}
}
Final Thoughts
Extension Members in C# 14 bring a new level of expressiveness and modularity to your code. Whether you're enhancing built-in types or creating domain-specific APIs, this feature helps you write cleaner, more maintainable code.
Have you tried Extension Members yet? Share your thoughts or examples in the comments!
Top comments (0)