How to use Generic Constraints

Generic Constraints

Sometimes you want to limit the types that can be used in a generic. You can do that using constraints:

  • where T : class – T must be a reference type.
  • where T : struct – T must be a value type.
  • where T : new() – T must have a parameterless constructor.
  • where T : SomeBaseClass – T must inherit from SomeBaseClass.
  • where T : SomeInterface – T must implement SomeInterface.
     
    public class MyClass<T> where T : class, new()
    {
        public T CreateInstance()
        {
            return new T();
        }
    }
    
    // Usage
    var myClass = new MyClass<MyType>();  // Assuming MyType is a class with a parameterless constructor
    

     

Up Next
    Ebook Download
    View all
    Learn
    View all