Say you are trying to read this property
var town = Staff.HomeAddress.Postcode.Town;
Somewhere along the chain a null could exist. What wo
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).