Let's assume I have a class that has a property of type Dictionary<string,string>
, that may be null.
This compiles but the call to TryGetValue()
could throw at a NullRef
exception at runtime:
MyClass c = ...;
string val;
if(c.PossiblyNullDictionary.TryGetValue("someKey", out val)) {
Console.WriteLine(val);
}
So I'm adding a null-propagating operator to guard against nulls, but this doesn't compile:
MyClass c = ...;
string val;
if( c.PossiblyNullDictionary ?. TryGetValue("someKey", out val) ?? false ) {
Console.WriteLine(val); // use of unassigned local variable
}
Is there an actual use case where val
will be uninitialized inside the if
block, or can the compiler simply not infer this (and why) ?
Update: The cleanest (?) way to workaround^H^H^H^H^H fix this is:
MyClass c = ...;
string val = null; //POW! initialized.
if( c.PossiblyNullDictionary ?. TryGetValue("someKey", out val) ?? false ) {
Console.WriteLine(val); // no more compiler error
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…