Reputation: 51
In the following example:
async Task Main()
{
// data can actually NEVER be null, but here it is of type Response?
var data1 = GetResponseData();
var data2 = await GetResponseDataAsync();
}
private Response GetResponseData()
{
var data = MyHelper("the method", m => GetData<Response>(m));
return data;
}
private Task<Response> GetResponseDataAsync()
{
var data = MyHelperAsync("the method", m => GetDataAsync<Response>(m));
// GIVES NULLABILITY WARNING HERE
return data;
}
class Response
{
public int prop { get; set; }
}
TResp? GetData<TResp>(string method)
{
return default(TResp);
}
TResp MyHelper<TResp>(string method, Func<string, TResp> getData)
{
var data = getData(method);
if (data is null)
throw new Exception("data should not be null");
return data;
}
in the main method the data variable is nullable, except that in reality it can never be null, and I'd like to force that knowledge.
I dont want to modify the GetData method as it CAN return null
[Edit] The solution also seems to work in the async case (surprisingly!): eg:
async Task Main()
{
var data2 = await MyHelperAsync("the method", m => GetDataAsync<Response>(m));
data2.prop.Dump();
}
class Response
{
public int prop { get; set; }
}
Task<TResp?> GetDataAsync<TResp>(string method)
{
return Task.FromResult(default(TResp));
}
[return: System.Diagnostics.CodeAnalysis.NotNull]
async Task<TResp> MyHelperAsync<TResp>(string method, Func<string, Task<TResp>> getData)
{
var data = await getData(method);
if (data is null)
throw new Exception("data should not be null");
return data;
}
Upvotes: 3
Views: 121
Reputation: 1499660
in the main method the data variable is nullable, except that in reality it can never be null, and I'd like to force that knowledge.
This is the sort of thing that the additional nullable attributes help with. In this case you want NotNull
applied to the return value:
[return:NotNull]
TResp MyHelper<TResp>(string method, Func<string, TResp> getData)
In a quick test, Visual Studio still shows the inferred type of data
as Response?
in Intellisense when you use var
, but it "knows" that it's not null (you can call data.ToString()
with no warnings for example) and you don't get any warnings if you explicitly specify the type of data
as Response
(whereas you would have done before). (This may be an Intellisense issue more than anything else.)
Upvotes: 5