Skip to content

EN CSharp Generics

Codex edited this page Oct 11, 2026 · 2 revisions

Українська · Русский · English · Deutsch · Français · Italiano · Español · 繁體中文 · 日本語 · 한국어

Generics and type restrictions

Manual C# · Examples UO

A generic type or method receives type parameters, for example T. The compiler checks calls to these types. Constraints where describe the necessary properties: base type, interface, class, struct, notnull, unmanaged, or accessible constructor new().

Simple example (Example.cs)

Save this example separately as Example.cs. Run it independently of the other examples on this page.

Example.cs:

// PROJECT-EXAMPLE
T Echo<T>(T value) => value;
System.Console.WriteLine(Echo(7));
System.Console.WriteLine(Echo("ore"));

Result:

7
ore
T FirstOrFallback<T>(IReadOnlyList<T> values, T fallback)
{
    return values.Count > 0 ? values[0] : fallback;
}

int first = FirstOrFallback(new[] { 10, 20 }, 0);
UO.Print(first.ToString());
sealed class Store<T> where T : notnull
{
    private readonly HashSet<T> values = new();
    public bool Add(T value) => values.Add(value);
    public int Count => values.Count;
}

var store = new Store<string>();
store.Add("self");
UO.Print(store.Count.ToString());

in and out for generic interfaces and delegates express contravariance and covariance; this is a different use of words than the parameters of the in/out method. They specify valid conversions of compatible reference types.

Official Documentation: Type Generics and Constraints - Microsoft Learn.

Clone this wiki locally