Designing Good Extensions
Apply best practices and avoid pitfalls.
Designing Good Extensions is a free C# Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C# Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Designing Extensions People Love
Extension methods are powerful, but power invites misuse. Good extensions feel like a natural part of the type, are easy to discover, and never surprise the caller. This lesson covers practical guidelines.
Extend Behavior, Not Identity
Prefer extensions for utility behaviors that read well in a pipeline. If a method truly belongs to a type you own, make it a real member instead.
using System;
public static class TimeExtensions
{
// A pleasant, focused helper
public static bool IsWeekend(this DayOfWeek day)
=> day == DayOfWeek.Saturday || day == DayOfWeek.Sunday;
}
public class Program
{
public static void Main()
{
Console.WriteLine(DayOfWeek.Sunday.IsWeekend());
Console.WriteLine(DayOfWeek.Monday.IsWeekend());
}
}Keep Methods Pure When Possible
Extensions that return a new value and avoid side effects are easiest to reason about and to chain. Aim for input-in, value-out.
using System;
public static class StringExtensions
{
// Pure: depends only on input, returns a new string
public static string Truncate(this string s, int max)
=> s.Length <= max ? s : s.Substring(0, max) + "...";
}
public class Program
{
public static void Main()
{
Console.WriteLine("Extension methods are great".Truncate(10));
}
}Guard Against Null Inputs
Because callers can invoke an extension on a null receiver, decide deliberately what should happen. Either tolerate null gracefully or throw a clear ArgumentNullException.
using System;
public static class StringExtensions
{
public static string SafeUpper(this string s)
{
if (s is null) throw new ArgumentNullException(nameof(s));
return s.ToUpper();
}
}
public class Program
{
public static void Main()
{
try { ((string)null).SafeUpper(); }
catch (ArgumentNullException ex) { Console.WriteLine("Caught: " + ex.ParamName); }
Console.WriteLine("ok".SafeUpper());
}
}Name for Discoverability
Developers find extensions by typing the dot and scanning IntelliSense. Clear, verb-based names that describe the result make your helpers discoverable and self-documenting.
using System;
using System.Collections.Generic;
public static class CollectionExtensions
{
public static bool HasItems<T>(this ICollection<T> c)
=> c != null && c.Count > 0;
}
public class Program
{
public static void Main()
{
var list = new List<int> { 1 };
Console.WriteLine(list.HasItems());
}
}Group Related Extensions Cohesively
Put extensions for one concept in one well-named static class and namespace. This keeps imports meaningful and lets users pull in exactly the helpers they want.
using System;
using System.Collections.Generic;
public static class EnumerableExtensions
{
public static IEnumerable<T> TakeFirst<T>(this IEnumerable<T> source, int n)
{
int taken = 0;
foreach (var item in source)
{
if (taken++ >= n) yield break;
yield return item;
}
}
}
public class Program
{
public static void Main()
{
var nums = new List<int> { 1, 2, 3, 4 };
Console.WriteLine(string.Join(",", nums.TakeFirst(2)));
}
}Do Not Hide Surprising Behavior
An extension that looks cheap but does expensive or stateful work violates expectations. Keep the cost obvious; if it queries a database or mutates state, name it accordingly.
using System;
public static class MathExtensions
{
// Cheap and obvious: no hidden cost
public static int ClampMin(this int value, int min)
=> value < min ? min : value;
}
public class Program
{
public static void Main()
{
Console.WriteLine((-3).ClampMin(0));
Console.WriteLine(5.ClampMin(0));
}
}Avoid Extending object
Extending object pollutes every type in the program with your method, cluttering IntelliSense everywhere. Target the most specific type or interface that makes sense instead.
using System;
public static class IntExtensions
{
// Specific to int, not object - far less noisy
public static string ToOrdinal(this int n)
{
if (n % 10 == 1 && n % 100 != 11) return n + "st";
if (n % 10 == 2 && n % 100 != 12) return n + "nd";
if (n % 10 == 3 && n % 100 != 13) return n + "rd";
return n + "th";
}
}
public class Program
{
public static void Main()
{
Console.WriteLine(1.ToOrdinal());
Console.WriteLine(22.ToOrdinal());
}
}Favor Returning IEnumerable for Sequences
For sequence operators, return IEnumerable<T> and use deferred execution. This composes well and avoids forcing callers to materialize data they may not need.
using System;
using System.Collections.Generic;
public static class SeqExtensions
{
public static IEnumerable<int> Doubled(this IEnumerable<int> source)
{
foreach (var n in source) yield return n * 2;
}
}
public class Program
{
public static void Main()
{
var nums = new List<int> { 1, 2, 3 };
foreach (var n in nums.Doubled()) Console.WriteLine(n);
}
}A Checklist for Good Extensions
Before shipping an extension ask: Is the name clear? Is it pure or are side effects obvious? Is null handled? Is the target type specific? Is it grouped sensibly? If yes to all, you have a helper others will enjoy using.
using System;
public static class StringExtensions
{
public static string OrDefault(this string s, string fallback)
=> string.IsNullOrEmpty(s) ? fallback : s;
}
public class Program
{
public static void Main()
{
Console.WriteLine("".OrDefault("N/A"));
Console.WriteLine("value".OrDefault("N/A"));
}
}Try It Yourself
Apply the checklist: a specific target type, a clear name, null tolerance, and a pure result. This small extension hits every guideline.
using System;
using System.Collections.Generic;
public static class DictionaryExtensions
{
// Clear name, specific type, null-safe, pure
public static TValue GetOrDefault<TKey, TValue>(
this IReadOnlyDictionary<TKey, TValue> dict, TKey key, TValue fallback)
{
if (dict == null) return fallback;
return dict.TryGetValue(key, out var value) ? value : fallback;
}
}
public class Program
{
public static void Main()
{
var ages = new Dictionary<string, int> { ["Ann"] = 30 };
Console.WriteLine(ages.GetOrDefault("Ann", -1));
Console.WriteLine(ages.GetOrDefault("Bob", -1));
}
}Quick Check
Apply the design guidelines.
Recap
Well-designed extensions feel native and predictable.
- Prefer pure, value-returning helpers that chain well.
- Decide and document null behavior.
- Use clear, verb-based names for discoverability.
- Target specific types or interfaces, not
object. - Group related helpers and return
IEnumerable<T>for sequences.
Frequently asked questions
Is the “Designing Good Extensions” lesson free?
Yes — the full text of “Designing Good Extensions” is free to read here on the web, and the C# Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C# Academy course, upgrade to CoddyKit PRO.
What will I learn in “Designing Good Extensions”?
Apply best practices and avoid pitfalls. You practise C# Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start C# Academy?
No prior experience is required. C# Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Designing Good Extensions” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this C# Academy lesson?
Yes. Every C# Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Defining Extension Methods
- Extending Interfaces and Generics
- Extension Method Resolution
- Designing Good Extensions