Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to allow nullable generic type in C# 8 as a return type for a method?

I have the following code:

public async Task<T> Retrieve<T>()
    where T : class, ITableEntity
{
    var result = await GetData<T>();
    return result.Result as T; // result.Result is object
}

Now the compiler gives a warning Possible null reference return. I can fix it with '!', but I actually do want to allow null, so it seems wrong to do it this way. I don't really know why does a compiler assume that class means non-nullable, I tried to write class? (don't even know what that means, but it compiles, though it gives the same warning).

Is it possible to tell compiler that T can be a nullable reference type? I guess it defaults to non-nullable.

like image 316
Ilya Chernomordik Avatar asked Nov 16 '25 08:11

Ilya Chernomordik


1 Answers

public async Task<T?> Retrieve<T>()
    where T : class, ITableEntity
like image 119
Marc Gravell Avatar answered Nov 18 '25 23:11

Marc Gravell