My situation is similar to the one described Proper nullable annotation for async generic method that may return default(T).
However, I'd like to know the proper way to let the caller know that the "return value" might be null.
public async Task<T> GetAsync<T>()
{
// sometimes returns default(T)!;
}
If this was not an async method I could use the MaybeNull attribute.
[return: MaybeNull]
public T Get<T>()
{
// sometimes returns default(T)!;
}
If it was not generic I could just use the ?
syntax.
public async Task<string?> GetAsync()
{
// sometimes returns default(string)!;
}
Is there a way to let the caller know that it could be null without adding a generic constraint?
EDIT: To clarify I mean let the compiler know that the value in the task may be null. I suppose the reverse is also true. I'm mostly interested in how this is supposed to work with the new C# nullable reference syntax.
I can do something like this just fine
var a = await GetAsync<string?>(); // a is null
var b = await GetAsync<int?>(); // b is null
var c = await GetAsync<string>(); // c is null. Wait string is not supposed to be null and the compiler won't warn you if you use it!
var d = await GetAsync<int>(); // d is 0
EDIT: I can do something like this just fine
var a = await Get<string?>(); // a is null
var b = await Get<int?>(); // b is null
var c = await Get<string>(); // c is null.
var d = await Get<int>(); // d is 0
The suggestion of Nullable reference types: How to specify "T?" type without constraining to class or struct is similar, but the Box class can be modified to provide the proper warnings where I cannot change the implementation of Task.