Reusable generic utilities
Build tiny, reusable helpers: Guard checks, key-based equality comparer, memoization for pure functions, and a simple Result .
Toolkit plan
Goal: Collect small helpers you can reuse across projects.
- Guard checks for arguments
- Key-based comparer for equality
- Memoize a pure function
- Result<T> for success/error flow
Guard checks
Centralize argument validation in a tiny Guard class; you call it at method start.
using System;
public static class Guard
{
public static T NotNull<T>(T value, string name) where T : class
{
if (value == null) throw new ArgumentNullException(name);
return value;
}
public static string NotNullOrEmpty(string value, string name)
{
if (string.IsNullOrEmpty(value)) throw new ArgumentException("must not be null or empty", name);
return value;
}
}
public class Program
{
public static void Main(string[] args)
{
// OK
string name = Guard.NotNullOrEmpty("Ada", "name");
Console.WriteLine("Hello, " + name);
// Uncomment to see guard throw:
// Guard.NotNull<string>(null, "input");
}
}
All lessons in this course
- unmanaged, notnull, new() (C# 6 emulation)
- Generic math (overview), generic attributes (when relevant)
- Reusable generic utilities