Constrain generic type parameters in C#

A generic constraint states what a type argument must support. Prefer the smallest contract your algorithm needs rather than checking the type at runtime.

An interface constraint exposes useful members. A new() constraint additionally allows construction through a public parameterless constructor.

Compile a constrained factory

In a .NET console project, replace Program.cs and run dotnet run:

C#
Console.WriteLine(CreateNamed<Item>("Example").Name);

static T CreateNamed<T>(string name)
	where T : class, INamed, new() {
	var item = new T();
	item.Name = name;
	return item;
}

public interface INamed { string Name { get; set; } }
public sealed class Item : INamed { public string Name { get; set; } = ""; }

The output is Example. Replacing Item with string fails compilation because string does not satisfy the interface and constructor requirements.

Choose value and nullability rules separately

Use where T : struct for a nonnullable value type. Use where T : class for a nonnullable reference type in a nullable-enabled project, or class? if nullable reference arguments are intended. notnull admits both nonnullable value and reference types. These are compile-time contracts, not runtime null guards for arbitrary callers.

Put base-class or interface requirements where the method genuinely uses them. new() comes after the other ordinary constraints and cannot be combined with struct, which already implies construction. Use a supplied factory delegate when construction requires arguments instead of forcing a parameterless constructor into the model.

Official references

Constraints on type parameters - C#
Learn about constraints on type parameters. Constraints tell the compiler what capabilities a type argument must have.
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/constraints-on-type-parameters
Generic constraints

Author: Herman Schoenfeld