Reputation: 39354
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?
Upvotes: 0
Views: 1676
Reputation: 154995
TryGetRule
returns false
that the out rule
parameter will be assigned to null
.
out PluralizationRuleDelegate rule
:
PluralizationRuleDelegate?
- i.e. "rule
can be null
".[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
.
[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;
}
Upvotes: 3