General restrictions for types that are not null

I have the following class:

public class KeyDTO<T>
{
     public T Id { get; set; }
}

So far, so good, but I want a parameter of type T to be non-empty. I read somewhere that this is possible:

public class KeyDTO<T> where T : IComparable, IComparable<T>
{
     public T Id { get; set; }
}

But, if I change public T Idto public T? Id, I get a compilation error telling me that it Tshould be non-null.

How can I indicate that a parameter of a generic type must be invalid?

Edit

I want to accomplish this because I want to annotate a property Idwith an attribute [Required]as follows:

public class KeyDTO<T> {
    [Required]
    public T Id { get; set; }
}

What [Required]it does is model validation, so Tit cannot be null.

However, if I have KeyDTO<int>, it Idwill be initialized to 0bypassing my attribute[Required]

+4
1

where T : struct , T , NULL. , , , " , ". (.. Nullable<T>) struct.

+12

All Articles