Home > Software engineering >  NET 6 - Nullability of reference types warning
NET 6 - Nullability of reference types warning

Time:05-25

In NET 6, I have a repository asynchronously returns string, which may be sourced from REST API or text file. Since the result could be null, the return type is nullable string in a task Task<string?>:

public interface IFooRepository
{
    Task<string?> FetchAsync(string path);
}

One of a concrete class of the repository would look like:

public class FooRepository : IFooRepository
{
    public async Task<string?> FetchAsync(string path)
    {
        string? result = null;

        if (File.Exists(path))
        {
            result = await File.ReadAllTextAsync(path);
        }

        return result;
    }
}

Next, I added a mock repository class used by the unit test. This simply returns the constant value. (Obviously, it will never return null.)

public class MockFooRepository : IFooRepository
{
    public Task<string?> FetchAsync(string path)
    {
        string? result = "ok!";
        return Task.FromResult(result);
    }
}

After adding the mock repository, I started to receive the warning message:

Nullability of reference types in value of type 'Task' doesn't match target type 'Task<string?>'.

To take care the warning, I prefer not to hide the warning message using preprocessor directives #pragma warning disable CS8619.

Instead, what would be the right way to handle the issue?

CodePudding user response:

Specify the generic argument yourself when calling FromResult

return Task.FromResult<string?>(result);
  • Related