Elegant way of reading a child property of an object

前端 未结 11 1231
半阙折子戏
半阙折子戏 2020-12-24 02:19

Say you are trying to read this property

var town = Staff.HomeAddress.Postcode.Town;

Somewhere along the chain a null could exist. What wo

11条回答
  •  太阳男子
    2020-12-24 02:22

    How often do you expect a null? If (and only if) it will be infrequent, I would use

    try
    {
        var town = staff.HomeAddress.Postcode.Town;
        // stuff to do if we could get the town
    }
    catch (NullReferenceException)
    {
        // stuff to do if there is a null along the way
    }
    

提交回复
热议问题