Confused about behavior of ?. operator

前端 未结 2 1452
灰色年华
灰色年华 2021-01-19 07:29

Here is my code

class Address
{
    public bool IsAppartment { get; set; }
}

class Employee
{
    public string Name { get; set; }
    public Address Addres         


        
相关标签:
2条回答
  • 2021-01-19 08:12

    UPDATE What will be equivalent code for following using short cut operators?
    if (employee.Address != null && ? employee.Address.IsAppartment == true)

    if (employee?.Address?.IsAppartment == true)
    
    0 讨论(0)
  • 2021-01-19 08:29

    This is correct, the rest of the chain doesn't execute, null-coalescing operator ?? returns true. According to MSDN

    The null-coalescing operator ?? returns the value of its left-hand operand if it isn't null; otherwise, it evaluates the right-hand operand and returns its result.

    If you want to compare the result with either true or false (per your update) you can use

    if (employee?.Address?.IsAppartment == true)
    {
    }
    

    The left-hand operand returns Nullable<bool>, you can also read about it in MSDN

    0 讨论(0)
提交回复
热议问题