Home > Net >  Why does the compiler allow instantiation of generic class both with a nullable and non-nullable gen
Why does the compiler allow instantiation of generic class both with a nullable and non-nullable gen

Time:07-04

I have a project in ASP.NET Core 6.

I have the <Nullable>enable</Nullable> setting in the project.

I have the following class:

public class ResponseResult<T> 
{
    public T? Result{ get; set; }
}

I can instantiate the class with a nullable or non-nullable generic parameter and the compiler does not generate a warning about it:

var a = new ResponseResult<WeatherForecast>();
var a2 = new ResponseResult<WeatherForecast?>();

My question is: why doesn't the compiler generate an error in the first case?

Since public T? Result{ get; set; } is nullable, shouldn't I be allowed to instantiate this class only with a nullable generic parameter?

CodePudding user response:

This is the expected behaviour. I don't see why it should be a problem.

For <WeatherForecast>, T is WeatherForecast and T? is WeatherForecast?.

For <WeatherForecast?>, both T and T? are WeatherForecast?.

When you declared the class this way:

public class ResponseResult<T> 
{
    public T? Result{ get; set; }
}

You didn't say "T must be nullable for the entire ResponseResult class", you said "Result is a property of type T, and the property is nullable if T is a reference type".

As far as I know, there is no way to actually constrain the generic type argument to have to be nullable. There is no need, as you can just use T? inside the class.

  • Related