0Pricing
C# Academy · Lesson

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

  1. unmanaged, notnull, new() (C# 6 emulation)
  2. Generic math (overview), generic attributes (when relevant)
  3. Reusable generic utilities
← Back to C# Academy