What is the "class" restriction on a generic type?

Asked

Viewed 150 times

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 interface IComparable, i.e., I am creating a generic type definition that implements what has been defined in the interface IComparable as a method and/or properties.

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

public class Repository<T> : IDisposable where T : class
  • 1

    You can do public class Repository<T> : IDisposable where T : classeExpecifica but this makes it T is no longer generic.

  • 1

    @true ramaral still would be generic, because it would allow any type that is descending from the specified class and not only the class.

  • Thanks @ramaral, helped a lot!

  • @Thanks for the correction.

1 answer

6


You can use any class and no more than this. You cannot use types other than a class, i.e., types other than a reference (although this definition is not quite true anymore because there is now type by reference that is not a class). In fact if you could use any type the constraint would not need to be written, but in this case types by value cannot be used as specific type in the class Repository.

Despite the name, it is not only classes that can be used, other types can be used by reference, such as interfaces, delegates and array, but can not a ref struct (at least for the time being).

Read more on documentation.

  • Got it, thanks mustache.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.