为什么Null Coalesce运算符仍然返回null?

时间:2016-06-01 13:05:25

标签: c# nullreferenceexception null-coalescing-operator

我有这个例程:

    try
    {
        CurrentSessionName = SelectedSession?.Name ?? "No Session Selected";
        CurrentSessionTolerance = SelectedSession?.Tolerance.ToString() ?? "N/A";
        CurrentSessionVerification = SelectedSession?.Verification.Description ?? "N/A";
    }
    catch (Exception ex)
    {
        var whatever = ex.GetType(); // hits here with no provided information
        Console.WriteLine("Null Reference Exception"); // ignores this
        string name = SelectedSession?.Name; // and this
    }

那么,即使NullReferenceException不是空的,为什么它仍会抛出SelectedSession错误?

2 个答案:

答案 0 :(得分:5)

空传播算子很棒 - 但它并没有神奇地消除空值。

此代码段

SelectedSession?.Tolerance

如果SelectedSession为空,则不会出错,但会传播,以便上述结果为空。如果SelectedSession 为null,但Tolerence为空,则同样适用。

问题是您尝试在空

上调用ToString()
SelectedSession?.Tolerance.ToString()

答案 1 :(得分:3)

ToleranceVerification可以为null,并且您在空指针上调用ToString()函数。

您无法在空指针上调用ToString()