What does where T : somevalue
mean? I just saw some code that said where T : Attribute
. I think this has something to do with generics but I am not sure what this means or what it is doing.
Does anyone know?
c++constraintsgenerics
What does where T : somevalue
mean? I just saw some code that said where T : Attribute
. I think this has something to do with generics but I am not sure what this means or what it is doing.
Does anyone know?
Best Answer
It is a constraint on a type parameter, meaning that the type
T
given to a generic class or method must inherit from the classAttribute
For example:
This is useful, because it allows the generic class to do things with objects of type
T
with the knowledge that anything that is aT
must also be anAttribute
.In the example above, it's okay for
GetTypeId
to query theTypeId
ofattr
becauseTypeId
is a property of anAttribute
, and becauseattr
is aT
it must be a type that inherits fromAttribute
.Constraints can also be used on generic methods, with the same effect:
There are other constraints you can place on a type; from MSDN: