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.
Usage Example
Section titled “Usage Example”using System;
// Multiple constraints illustrated in a classpublic 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); }}Output console
Section titled “Output console”dotnet runTrueImportant notes
Section titled “Important notes”- Constraints are optional but powerful.
- Constraints can be applied to the class or the method.
- Multiple constraints are separated by commas.
Real-world usage example
Section titled “Real-world usage example”Dictionary<TKey, TValue> – TKey cannot be null (implicit constraint).
See .NET docs on constraints.