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
TryGetRulereturnsfalsethat theout ruleparameter will be assigned tonull.- ...in that case you need to add two annotations to
out PluralizationRuleDelegate rule:PluralizationRuleDelegate?- i.e. "rulecan benull".[NotNullWhen(true)]- i.e. "Even though we've declaredruleas maybe-null, we pinky-swear promise that when this method returnstruethat theout ruleparameter will not benull.- 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 != nullchecks to every this.Rules.TryGetValue` call-site too.
- Note that the C# compiler does not (and cannot, I think?) exhaustively prove your
- ...in that case you need to add two annotations to
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;
}
