C# Generics Tutorial (.NET 10): Constraints and Errors

Last updated: October 17, 2026 · Tested with .NET 10 (SDK 10.0.401, runtime 10.0.12), C# 14, BenchmarkDotNet 0.15.2, Windows 11

Short answer: Generics let you write a class or method once with a type parameter (T) and have the compiler check every use. List<int> can’t hold a string, and it doesn’t box its values. In my test, 100,000 ints took 400,056 bytes in List<int> and 3,200,080 bytes in ArrayList. Constraints (where T : ...) tell the compiler what T can do. Most generic compiler errors (CS0403, CS0019, CS0310, CS0311, CS0452) mean a constraint is missing or wrong. Every example below was compiled and run on .NET 10, and the errors are copied from the real compiler output.

Why Generics: Type Safety and No Boxing, Measured

Before generics, collections stored object. The compiler accepted anything, and mistakes showed up at runtime:

var mixed = new ArrayList { 42, "hello" };
int n = (int)mixed[1]!;   // compiles
InvalidCastException: Unable to cast object of type 'System.String' to type 'System.Int32'.

With List<int>, numbers.Add("hello") doesn’t compile, and reading an item needs no cast. The second benefit is memory. Each int added to an ArrayList is boxed into its own heap object. I measured 100,000 adds with GC.GetAllocatedBytesForCurrentThread(), with capacity preset so list growth isn’t counted:

ArrayList, 100,000 ints: 3,200,080 bytes
List<int>, 100,000 ints: 400,056 bytes

That’s 8× the memory: 24 bytes per boxed int plus an 8-byte reference, against 4 bytes per int in the generic list’s backing array.

Generic Classes

The type parameter goes in angle brackets after the class name. Callers pick the type, and the compiler checks every use:

public class Box<T>
{
    private T _content = default!;
    public void Put(T item) => _content = item;
    public T Take() => _content;
}

var intBox = new Box<int>();
intBox.Put(100);
int value = intBox.Take();   // no cast

Use several parameters with descriptive names when there’s more than one, as in Dictionary<TKey, TValue>. At runtime, .NET creates one specialized copy of the code per value type (Box<int>, Box<double>) and shares one copy across all reference types.

Each closed type has its own static fields

static class Counter<T>
{
    public static int Count;
    public static void Increment() => Count++;
}

Counter<int>.Increment(); Counter<int>.Increment(); Counter<string>.Increment();
Counter<int>.Count = 2, Counter<string>.Count = 1

This surprises people who put a cache or a counter in a generic class and expect it to be shared. It isn’t: Counter<int> and Counter<string> are different types. (It’s also a handy trick for per-type caches.)

Generic Methods and Type Inference

static class Swapper
{
    public static void Swap<T>(ref T a, ref T b) => (a, b) = (b, a);
}

int x = 1, y = 2;
Swapper.Swap(ref x, ref y);   // T inferred as int
// After Swap: x=2, y=1

The compiler infers T from the arguments, which is why LINQ’s Where and Select never need explicit types. It can’t infer from a return type alone. See CS0411 in the error section.

Constraints: What T Is Allowed to Do

Without a constraint, the compiler only lets you use object members on T. A constraint is a promise that unlocks more:

public interface IEntity
{
    int Id { get; set; }
    DateTime CreatedAt { get; set; }
}

public class Repository<T> where T : class, IEntity, new()
{
    private readonly List<T> _items = new();

    public T Create()
    {
        var item = new T();                  // allowed because of new()
        item.CreatedAt = DateTime.UtcNow;    // allowed because of IEntity
        _items.Add(item);
        return item;
    }

    public T? FindById(int id) => _items.FirstOrDefault(x => x.Id == id);
}
Repository<Product>: found Id 7, CreatedAt set: True
ConstraintMeansSince
where T : class / class?Reference type (non-nullable / nullable)C# 2 / C# 8
where T : structNon-nullable value typeC# 2
where T : IComparable<T>Implements the interface (the most common)C# 2
where T : BaseClassDerives from the classC# 2
where T : new()Public parameterless constructorC# 2
where T : notnullNon-nullable type (warning-level check)C# 8
where T : unmanagedValue type with no references, usable with pointers and spansC# 7.3
where T : Enum / DelegateAny enum / any delegateC# 7.3
where T : INumber<T>Generic math (static abstract interface members)C# 11, .NET 7
where T : allows ref structAnti-constraint: T may be a ref struct such as Span<int>C# 13

If you find yourself casting T inside a generic method, add a constraint instead. Constraints also document what callers may pass. For when to use an interface and when to use a base class, see interface vs abstract class.

Generic math: one Sum for every numeric type

using System.Numerics;

static class MathHelpers
{
    public static T Sum<T>(IEnumerable<T> values) where T : INumber<T>
    {
        T total = T.Zero;
        foreach (T v in values) total += v;
        return total;
    }
}
Sum<int>: 6, Sum<decimal>: 3.75, Sum<double>: 0.30000000000000004

Before .NET 7 this needed one overload per numeric type, or dynamic. T.Zero and += work because INumber<T> declares them as static abstract members. The double result is ordinary floating-point rounding, not a generics problem.

The Equality Trap: == on a Generic T

Unconstrained a == b doesn’t compile (CS0019, below). Add where T : class and it compiles, but it compares references, even for string:

static class Compare
{
    public static bool SameRef<T>(T x, T y) where T : class => x == y;            // reference comparison
    public static bool Same<T>(T x, T y) => EqualityComparer<T>.Default.Equals(x, y);
}

string a = "generics", b = new string("generics".ToCharArray());
a == b (string):            True
SameRef<string>(a, b):       False
Same<string>(a, b):          True

Inside the generic method, the compiler doesn’t know T is string, so it can’t call string‘s == operator. It emits a reference comparison instead. Use EqualityComparer<T>.Default.Equals: it works for value and reference types and respects Equals overrides and IEquatable<T>.

Variance: Why List<string> Isn’t a List<object>

List<string> names = new();
List<object> objects = names;                   // CS0029

IEnumerable<object> readOnly = names;           // compiles: IEnumerable<out T> is covariant

Generic classes are invariant. If the first assignment were allowed, you could Add(42) to a list of strings. Interfaces that only return T can be declared covariant (out T), like IEnumerable<out T>. Interfaces that only accept T can be contravariant (in T), like IComparer<in T>.

Common C# Generic Compiler Errors and Fixes

I wrote code that triggers each error and copied the messages from dotnet build on SDK 10.0.401. The fixes are in a separate project that builds with zero warnings under -warnaserror.

CS0403: Cannot convert null to type parameter ‘T’

public static T Find<T>(List<T> items, int index)
{
    if (index >= items.Count) return null;   // CS0403
    return items[index];
}
error CS0403: Cannot convert null to type parameter 'T' because it could be a non-nullable value type. Consider using 'default(T)' instead.

Fix: return default and mark the return type T?. That gives null for reference types and 0/false for value types. If you really mean “null”, constrain with where T : class.

public static T? Find<T>(List<T> items, int index) => index < items.Count ? items[index] : default;

Watch the value-type case: a FirstOrDefault-style method returned 0 for “not found” in an int[], which is indistinguishable from a real 0. Return a bool plus an out T (the TryGetValue pattern) when 0 is a valid value. For how T? behaves with nullable reference types, see C# nullable reference types.

CS0019: Operator ‘==’ cannot be applied to operands of type ‘T’ and ‘T’

public static bool Same<T>(T a, T b) => a == b;   // CS0019
error CS0019: Operator '==' cannot be applied to operands of type 'T' and 'T'

Fix: EqualityComparer<T>.Default.Equals(a, b). Don’t fix it by adding where T : class; see the equality trap above. For numbers, where T : INumber<T> also makes == available.

CS0310: must be a non-abstract type with a public parameterless constructor

public class Widget { public Widget(string name) { } }
public class Factory<T> where T : new() { public T Create() => new T(); }

public static Factory<Widget> F = new();   // CS0310
error CS0310: 'Widget' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'Factory<T>'

Fix: add a parameterless constructor if it makes sense for the type. Otherwise drop new() and take a factory delegate, which can also pass constructor arguments:

public class Factory<T>(Func<T> create)
{
    public T Create() => create();
}

public static Factory<Widget> F = new(() => new Widget("default"));

CS0311: no implicit reference conversion from ‘Customer’ to ‘IEntity’

public class Customer { public int Id { get; set; } }
public class Repo<T> where T : IEntity { }

public static Repo<Customer>? R;   // CS0311
error CS0311: The type 'Customer' cannot be used as type parameter 'T' in the generic type or method 'Repo<T>'. There is no implicit reference conversion from 'Customer' to 'IEntity'.

Fix: have the type implement the interface (public class Customer : IEntity). Having an Id property with the same name isn’t enough; C# constraints aren’t duck-typed.

CS0452: The type ‘int’ must be a reference type

public class RefOnly<T> where T : class { }
public static RefOnly<int>? R;   // CS0452
error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'RefOnly<T>'

Fix: pass a reference type, or remove the class constraint if the code doesn’t need it. Often it was only added to make null or == compile; use default and EqualityComparer<T> instead. The mirror error for where T : struct is CS0453.

CS1061: ‘T’ does not contain a definition for ‘Id’

public static int GetId<T>(T item) => item.Id;   // CS1061
error CS1061: 'T' does not contain a definition for 'Id' and no accessible extension method 'Id' accepting a first argument of type 'T' could be found (are you missing a using directive or an assembly reference?)

Fix: constrain T to an interface or base class that declares the member: public static int GetId<T>(T item) where T : IEntity => item.Id;

CS0411: The type arguments cannot be inferred from the usage

public static T Create<T>() => default!;
var x = Create();   // CS0411
error CS0411: The type arguments for method 'E8_Inference.Create<T>()' cannot be inferred from the usage. Try specifying the type arguments explicitly.

Fix: write Create<int>(). C# infers type arguments from method arguments, never from the variable you assign the result to.

CS0029: Cannot implicitly convert List<string> to List<object>

error CS0029: Cannot implicitly convert type 'System.Collections.Generic.List<string>' to 'System.Collections.Generic.List<object>'

Fix: use IEnumerable<object> or IReadOnlyList<object> for read-only access (both covariant), or build a new list with names.Cast<object>().ToList(). See the variance section above.

Is new T() Slow? Measured

The new() constraint compiles to a call to Activator.CreateInstance<T>(). I checked the IL of static T Create<T>() where T : new() => new T(); and found exactly one call: System.Activator.CreateInstance[T](). BenchmarkDotNet (ShortRun job, .NET 10, creating a small class):

| Method        | Mean     | Allocated |
|-------------- |---------:|----------:|
| Direct        | 3.529 ns |      24 B |
| NewConstraint | 6.570 ns |      24 B |
| FuncFactory   | 3.766 ns |      24 B |

On .NET 10, new T() took about twice as long as a direct new, and a cached Func<T> factory was close to direct. ShortRun uses only 3 iterations, so treat these as rough numbers (the reported error is several nanoseconds). Either way the difference is a few nanoseconds per object. It matters only in hot loops that create millions of objects. The stronger reason to prefer a factory is the one from CS0310: it can pass constructor arguments.

Real-World Pattern: Result<T>

class Result<T>
{
    public bool IsSuccess { get; }
    public T? Value { get; }
    public string? Error { get; }
    private Result(bool ok, T? value, string? error) => (IsSuccess, Value, Error) = (ok, value, error);
    public static Result<T> Success(T value) => new(true, value, null);
    public static Result<T> Failure(string error) => new(false, default, error);
}

static Result<Order> Place(int itemCount) =>
    itemCount == 0 ? Result<Order>.Failure("Cart is empty.") : Result<Order>.Success(new Order(itemCount));
Order placed: 3 items
Failed: Cart is empty.

A result type makes expected failures part of the method signature instead of an exception. For the generic repository over EF Core (IRepository<T> registered as services.AddScoped(typeof(IRepository<>), typeof(EfRepository<>))), see the repository pattern guide.

Open and Closed Generic Types (Reflection and DI)

Type open = typeof(List<>);
Type closed = open.MakeGenericType(typeof(int));
List`1 IsGenericTypeDefinition=True; System.Collections.Generic.List`1[System.Int32] == typeof(List<int>): True

typeof(List<>) is the open definition. You need it for open-generic DI registrations like the repository above. MakeGenericType closes it at runtime. Note the CLR name List`1: the backtick and number are the generic arity, which you’ll see in stack traces and logs.

Best Practices

  • Name type parameters T when there’s one; otherwise use TKey, TValue, TEntity, TResult.
  • Prefer constraints over casts and is checks inside generic code.
  • Compare with EqualityComparer<T>.Default, never == on a class-constrained T.
  • Return T? with default, and use the TryGet pattern when default is a valid value.
  • Don’t make a type generic until there are at least two real type arguments for it.
  • Expose read-only collections as IEnumerable<T> or IReadOnlyList<T> so callers get covariance.

FAQ

What does <T> mean in C#?
T is a type parameter: a placeholder the caller replaces with a real type, as in List<int>. The name is a convention; any identifier works.

Do generics make code faster?
For value types, yes: no boxing (8× less memory in the ArrayList test above) and no casts. For reference types the gain is mainly type safety, since there was no boxing to remove.

Why can’t I return null from a generic method?
Because T might be int. Return default (error CS0403 above), or add where T : class.

Can I use arithmetic on T?
Yes, since .NET 7: constrain to INumber<T> (or a narrower interface like IAdditionOperators<T, T, T>) and use +, T.Zero and friends.

Conclusion

Generics give you compile-time checking and, for value types, much less memory: 400 KB against 3.2 MB for 100,000 ints in my test. Most generic compiler errors come down to one question: what does the compiler know about T? Add the right constraint, use default instead of null and EqualityComparer<T> instead of ==, and most of them go away. Newer features build on the same idea: C# 13’s allows ref struct lets generic code accept spans, and LINQ is generic methods all the way down (LINQ examples on .NET 10).

References: Generic classes and methods · Constraints on type parameters · Generic math · Covariance and contravariance in generics · Compiler errors for generic type parameters

This article is part of the C# tutorials guide (language features, patterns, performance and testing).

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *