Home > Net >  Cannot convert null literal to non-nullable reference type
Cannot convert null literal to non-nullable reference type

Time:10-08

Using C# 10 I have the interface:

public interface IPluralRuleProvider {
    Boolean TryGetRule(CultureInfo culture, out PluralizationRuleDelegate rule);
}

In a class I am implementing the method and I have:

Rules = new Dictionary<String, PluralizationRuleDelegate>();

Boolean IPluralRuleProvider.TryGetRule(CultureInfo culture, out PluralizationRuleDelegate rule)
{
    rule = null;

    if (Rules.TryGetValue(culture.Name, out rule))
        return true;    

    if (culture.Parent != null && Rules.TryGetValue(culture.Parent.Name, out rule))
        return true;

    return false;
}

I am getting the warnings:

Cannot convert null literal to non-nullable reference type
Possible null reference assignment

I have been trying different versions but I always get some kind of warning.

Can I change something to avoid this?

CodePudding user response:

  • I assume when TryGetRule returns false that the out rule parameter will be assigned to null.
    • ...in that case you need to add two annotations to out PluralizationRuleDelegate rule:
      1. PluralizationRuleDelegate? - i.e. "rule can be null".
      2. [NotNullWhen(true)] - i.e. "Even though we've declared rule as maybe-null, we pinky-swear promise that when this method returns true that the out rule parameter will not be null.
        • Note that the C# compiler does not (and cannot, I think?) exhaustively prove your [NotNullWhen(true)] postcondition - so be sure to double-check your logic - consider adding && rule != null checks to every this.Rules.TryGetValue` call-site too.

Anyway, change your interface to this:

using System.Diagnostics.CodeAnalysis;

public interface IPluralRuleProvider {
  Boolean TryGetRule(CultureInfo culture, [NotNullWhen(true)] out PluralizationRuleDelegate? rule);
}

and implementation:

using System.Diagnostics.CodeAnalysis;

Boolean IPluralRuleProvider.TryGetRule(CultureInfo culture, [NotNullWhen(true)] out PluralizationRuleDelegate rule) {

  if (this.Rules.TryGetValue(culture.Name, out rule))
    return true;

  if (culture.Parent != null && this.Rules.TryGetValue(culture.Parent.Name, out rule))
    return true;

  return false;
}
  • Related