Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
290 views
Welcome To Ask or Share your Answers For Others

1 Answer

Seems like you have run into a limitation of the compilers understanding of ?. and ?? which isn't too surprising, given that they aren't really fully incorporated in the language.

If you make your test explicit without the newer operators, the compiler will agree with you:

MyClass c = new MyClass();
string val;
if (c.PossiblyNullDictionary != null && c.PossiblyNullDictionary.TryGetValue("someKey", out val)) {
    Console.WriteLine(val); // now okay
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...