Reputation: 26281
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
Upvotes: 63
Views: 41262
Reputation: 2360
From C# 8.0 you can now use the where T : notnull
generic constraint to specificy T
is a non-nullable type.
Upvotes: 118
Reputation: 203821
Applying where T : struct
applies a generic constraint that T
be a non-nullable value type. Since there are no non-nullable reference types, this has the exact same semantics as simply "all non-nullable types". Nullable value types (i.e. Nullable<T>
) do not satisfy the struct
generic constraint.
Upvotes: 45