Recipe 15.1 · C#
Extension Methods Worth Keeping
Problem
Extension methods are easy to write and hard to remove. Teams collect dozens of them, many duplicating what the base class library already does. A few, though, remove real noise from everyday code and prevent real bugs. You want a small set you can carry from project to project, and a rule for saying no to the rest.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
// Not to copy: wrappers, surprises and swallowed errors.
public static class Extensions
{
public static bool IsEmpty(this string s)
{
return s == null || s == ""; // misses " "
}
public static int ToInt(this object o)
{
try { return Convert.ToInt32(o); }
catch { return 0; } // bad data becomes 0
}
public static bool In(this string s, params string[] list)
{
return list.Contains(s); // case-sensitive?
}
}
Each of these looks harmless. IsEmpty treats a string of spaces as valid input. ToInt turns "12,5", "abc" and null into zero without a trace. And because ToInt extends object, it shows up in IntelliSense on every variable in the solution.
The improved recipe
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
namespace ImproveCode.Utilities;
public static class CommonExtensions
{
public static bool HasText(
[NotNullWhen(true)] this string? value) =>
!string.IsNullOrWhiteSpace(value);
public static string? TrimToNull(this string? value)
{
if (value is null)
{
return null;
}
string trimmed = value.Trim();
return trimmed.Length == 0 ? null : trimmed;
}
public static bool EqualsIgnoreCase(
this string? value, string? other) =>
string.Equals(
value, other, StringComparison.OrdinalIgnoreCase);
public static IEnumerable<T> EmptyIfNull<T>(
this IEnumerable<T>? source) =>
source ?? Enumerable.Empty<T>();
public static IEnumerable<T> WhereNotNull<T>(
this IEnumerable<T?> source) where T : class =>
source.OfType<T>();
public static Dictionary<TKey, T> ToDictionaryFirstWins<TKey, T>(
this IEnumerable<T> source,
Func<T, TKey> keySelector,
IEqualityComparer<TKey>? comparer = null)
where TKey : notnull
{
ArgumentNullException.ThrowIfNull(source);
ArgumentNullException.ThrowIfNull(keySelector);
var result = new Dictionary<TKey, T>(comparer);
foreach (T item in source)
{
result.TryAdd(keySelector(item), item);
}
return result;
}
}
Usage snippet:
string? note = form.Note.TrimToNull(); // "" and " " -> null
if (customer.Email.HasText())
{
Send(customer.Email); // no null warning
}
var byCode = products.ToDictionaryFirstWins(
p => p.Code, StringComparer.OrdinalIgnoreCase);
How it works
HasText replaces the most common two-line check in business code and carries the [NotNullWhen(true)] attribute, so the compiler knows the string is not null inside the if. With nullable reference types on, that removes a whole category of ! operators.
TrimToNull normalizes form input at the boundary. Empty strings and whitespace become null, which is what you want to store in a nullable column. A database full of '', ' ' and NULL all meaning "no value" makes every later query harder.
EqualsIgnoreCase makes the comparison explicit. Ordinal comparison is the right default for codes, keys, file extensions and anything a machine produced. Culture-aware comparison is for sorting names shown to people.
EmptyIfNull lets a foreach run over a collection property that might be null, and WhereNotNull filters nulls while giving you a non-nullable element type. OfType<T>() already skips nulls, so the method is one line; the name just says what you mean.
ToDictionaryFirstWins exists because of a crash that turns up in a lot of codebases: ToDictionary throws "An item with the same key has already been added" the first time real data contains a duplicate. When duplicates are possible and the first row is the right one, say so in the method name.
Variations and pitfalls
- My rule for a new extension method: it must remove noise in at least three places, it must not hide a failure, and it must not extend
object. Most proposed extensions fail the first test. - Check the BCL before writing one.
Chunk,DistinctBy,MaxBy,GetValueOrDefault,TryAdd,string.JoinandEnumerable.ToHashSetreplaced a lot of homegrown helpers between .NET Core 2.0 and .NET 6. - Don't put extension methods in the
Systemnamespace to make them appear everywhere. Put them in your own namespace and import it where needed. - If
ToDictionaryFirstWinshides data quality problems you should fix, log the duplicates instead of silently dropping them.