Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic Constraint for Non Nullable types

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

like image 273
Matias Cicero Avatar asked Dec 15 '14 17:12

Matias Cicero


People also ask

What are generic type constraints?

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.

Can generic classes be constrained?

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.

How do you indicate that a class has a generic type parameter?

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.


1 Answers

From C# 8.0 you can now use the where T : notnull generic constraint to specificy T is a non-nullable type.

like image 153
nalka Avatar answered Oct 16 '22 07:10

nalka