Elegant way of reading a child property of an object

前端 未结 11 1228
半阙折子戏
半阙折子戏 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:33

    Here a solution using null coalescing operators that I put together for fun (other answers are better). If you except this as the answer I'll have to hunt you down and uh, take your keyboard away! :-)

    Basically, if any object in Staff is null its default will be used instead.

    // define a defaultModel
    var defaultModel = new { HomeAddress = new { PostCode = new { Town = "Default Town" } } };
    // null coalesce through the chain setting defaults along the way.
    var town = (((Staff ?? defaultModel)
                    .HomeAddress  ?? defaultModel.HomeAddress)
                        .PostCode ?? defaultModel.HomeAddress.PostCode)
                            .Town ?? defaultModel.HomeAddress.PostCode.Town;
    

    Disclaimer, I'm a javascript guy and we javascripters know that accessing an object's properties can get expensive - so we tend to cache just above everything, which is what the code above accomplishes (each property is only looked up once). With C#'s compilers and optimizers it probably isn't necessary to do it (some confirmation on this would be nice).

提交回复
热议问题