where T class (reference type)
Context: The constraint where T : class requires the type parameter to be a reference type (class, interface, delegate, array). It allows null. It is often used for containers that manage shared objects or require references.
Usage Example
Section titled “Usage Example”using System;using System.Collections.Generic;
public class Warehouse<T> where T : class{ private readonly List<T> _items = new List<T>();
public void Add(T item) { if (item == null) throw new ArgumentNullException(nameof(item)); _items.Add(item); }
public T Get(int index) => _items[index];}
class Program{ static void Main() { var stringWarehouse = new Warehouse<string>(); stringWarehouse.Add("Hello"); Console.WriteLine(stringWarehouse.Get(0));
// This does not compile: int is a struct // var intWarehouse = new Warehouse<int>(); }}Output console
Section titled “Output console”dotnet runHelloImportant notes
Section titled “Important notes”classincludes interfaces, delegates, and arrays.- Allows checking for
nulland using theasoperator.
Real-world usage example
Section titled “Real-world usage example”List<T> – Does not have a class constraint, but many custom collections use it to ensure elements are objects.
See .NET docs on class constraint.