I have the following class:
public class KeyDTO<T> { public T Id { get; set; } }
So far so good, but I want the type parameter T to be a non-nullable type. I've read somewhere that this may be feasible:
public class KeyDTO<T> where T : IComparable, IComparable<T> { public T Id { get; set; } }
But, If i change public T Id
to public T? Id
, I get a compilation error telling me that T
must be non-nullable.
How can I specify that a generic type parameter must be non-nullable?
I want to accomplish this because I want to annotate my Id
property with the [Required]
attribute as follows:
public class KeyDTO<T> { [Required] public T Id { get; set; } }
What [Required]
does is validate the model so T
cannot be null.
However, if I have KeyDTO<int>
, Id
will be initialized to 0
, bypassing my [Required]
attribute
C# allows you to use constraints to restrict client code to specify certain types while instantiating generic types. It will give a compile-time error if you try to instantiate a generic type using a type that is not allowed by the specified constraints.
You can constrain the generic type by interface, thereby allowing only classes that implement that interface or classes that inherit from classes that implement the interface as the type parameter. The code below constrains a class to an interface.
A generic type is declared by specifying a type parameter in an angle brackets after a type name, e.g. TypeName<T> where T is a type parameter.
From C# 8.0 you can now use the where T : notnull
generic constraint to specificy T
is a non-nullable type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With