What is the "class" constraint in a generic type?

5

In the line below:

public class Tree<TItem> where TItem : IComparable<TItem>

This line I'm creating the definition of type TItem where TItem implements the IComparable interface, ie I'm creating a generic type definition that implements what was defined in the interface IComparable as method e / or properties.

My question would be in the line below, where type T implements a class . Why does a class and not a specific class? What is the purpose of creating a definition for type T that implements a class ?

public class Repository<T> : IDisposable where T : class
    
asked by anonymous 15.09.2015 / 17:00

1 answer

6

Be able to use any class and not more than this. You can not use types other than a class, ie types other than a reference . In fact if you could use any type the constraint would not have to be written, but in this case types by value can not be used as specific type in class Repository .

Despite the name, not only are classes that can be used, they can be other types by reference, such as interfaces, delegates and array .

Read more in documentation .

    
15.09.2015 / 17:04