Sanan Fataliyev
Sanan Fataliyev

Reputation: 630

C# null propagation operator inside if condition statement

Let's say I want to write something like:

    static string Foo(dynamic d, string key)
    {
        var dict =  d as IDictionary<string, string>;

        if (dict?.TryGetValue(key, out string result) ?? false)
        {
            return result;
        }

        return null;
    }

It gives compile error: Local variable 'result' migth not be initialized before accessing

I wonder why c# compiler doesn't sure about the control flow in this case.

We all know that most of time c# compiler behaves "smart" when it sees constant values.

Upvotes: 0

Views: 36

Answers (0)

Related Questions