Null propagation operator, out parameters and false compiler errors?

前端 未结 3 867
花落未央
花落未央 2020-12-09 12:17

Let\'s assume I have a class that has a property of type Dictionary, that may be null.

This compiles but the call to TryGetVa

3条回答
  •  生来不讨喜
    2020-12-09 12:44

    By initializing val to a erhm, value (e.g., String.Empty) the compiler is able to grok the intent for the null operators and behaves as expected (via LINQPad, natch):

    void Main()
    {
        MyClass c = new MyClass();
        string val = string.Empty;
        if (c.PossiblyNullDictionary?.TryGetValue("someKey", out val) ?? false)
        {
    
            Console.WriteLine(val);
    
        }
    }
    public class MyClass {
        public Dictionary PossiblyNullDictionary;
    }
    // Define other methods and classes here
    

    Ed: by 'grok the intent' I meant that the compiler can't make important guarantees about the program's characteristics if it allows execution to leave the current scope with val uninitialized. When it evaluates the null operators, the method invocation.

    The use case you ask for is this: Say that instead of TryGetValue, we have bool SomeMethod(string s, out v). Let's say that when invoked, SomeMethod is naughty and simply has a body of return true;. The compiler treats method invocation bodies as opaque (since it may not always be in an assembly available/visible to the compiler), so it concludes that there's no way to prove that val is ever initialized.

    ed: In response to some comments, I wanted to update my answer to point out that this behavior isn't specific to the ?? or ?. C# language features; you can reproduce the same effect simply by using a ternary expression:

    c.PossiblyNullDictionary == null ? 
        false : 
        c.PossiblyNullDictionary.TryGetValue("someKey", out val) 
     //error: use of possibly uninitialized local variable
    

提交回复
热议问题