In C#, say that you want to pull a value off of PropertyC in this example and ObjectA, PropertyA and PropertyB can all be null.
ObjectA.PropertyA.PropertyB.PropertyC
How can I get PropertyC safely with the least amount of code?
Right now I would check:
if(ObjectA != null && ObjectA.PropertyA !=null && ObjectA.PropertyA.PropertyB != null)
{
// safely pull off the value
int value = objectA.PropertyA.PropertyB.PropertyC;
}
It would be nice to do something more like this (pseudo-code).
int value = ObjectA.PropertyA.PropertyB ? ObjectA.PropertyA.PropertyB : defaultVal;
Possibly even further collapsed with a null-coalescing operator.
EDIT Originally I said my second example was like js, but I changed it to psuedo-code since it was correctly pointed out that it would not work in js.
Question&Answers:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…