Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

NET 6 – Nullability of reference types warning

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.)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

Specify the generic argument yourself when calling FromResult

return Task.FromResult<string?>(result);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading