Skip to content

Constraints

Context: Constraints restrict the types that can be used as generic type arguments. They allow accessing specific members (constructors, methods, properties) of the type parameter. The where clause is used to declare constraints.

using System;
// Multiple constraints illustrated in a class
public class ConstraintDemo<T> where T : class, new()
{
public T CreateInstance()
{
return new T(); // new() allows using the parameterless constructor
}
}
class Program
{
static void Main()
{
var demo = new ConstraintDemo<ConstraintDemo<object>>();
var instance = demo.CreateInstance();
Console.WriteLine(instance != null);
}
}
Terminal window
dotnet run
True
  • Constraints are optional but powerful.
  • Constraints can be applied to the class or the method.
  • Multiple constraints are separated by commas.

Dictionary<TKey, TValue>TKey cannot be null (implicit constraint).
See .NET docs on constraints.