Skip to content

Should CacheExtensions.GetOrCreate()/GetOrCreateAsync() return TItem instead of TItem?? #77266

Description

@kevinchalet

Take this snippet:

using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.DependencyInjection;

var services = new ServiceCollection();
services.AddMemoryCache();

var provider = services.BuildServiceProvider();
var cache = provider.GetRequiredService<IMemoryCache>();

var instance = cache.GetOrCreate("key", entry =>
{
    // ...
    return new
    {
        Message = "Hello World"
    };
});

Console.WriteLine(instance.Message);

On .NET 6.0, you don't get any error or warning as the caching stack was not decorated with nullable annotations.
On .NET 7.0, you get a CS8602 warning on the last line, as GetOrCreate() returns TItem? even if the delegate itself will never return null.

I guess the warning is technically correct because - in theory - nothing prevents me from inserting a null value in the cache before the delegate has a chance to be called, but I'm not sure it's a frequent case (in this case, it would be more logical that the delegate signature use TItem? instead of TItem to account for potential null values).

To make them easier to use, should CacheExtensions.GetOrCreate()/GetOrCreateAsync() return TItem instead of TItem??

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions