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?
Edit
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