Nullable reference types with generic return type

前端 未结 3 1416
忘掉有多难
忘掉有多难 2020-11-27 18:39

I\'m playing around a bit with the new C# 8 nullable reference types feature, and while refactoring my code I came upon this (simplified) method:

public T Get         


        
3条回答
  •  孤城傲影
    2020-11-27 19:02

    You were very close. Just write your method like this:

    [return: MaybeNull]
    public T Get(string key)
    {
        var wrapper = cacheService.Get(key);
        return wrapper.HasValue ? Deserialize(wrapper) : default!;
    }
    

    You have to use the default! to get rid of the warning. But you can tell the compiler with [return: MaybeNull] that it should check for null even if it's a non-nullable type.

    In that case, the dev may get a warning (depends on flow analytics) if he uses your method and does not check for null.

    For further info, see Microsoft documentation: Specify post-conditions: MaybeNull and NotNull

提交回复
热议问题