Another, albeit not very nice option (apart from re-designing your code, see Mehrdad Afshari's answer) would be to use a try..catch
block to see if a NullReferenceException
occurs sometime during that deep property lookup.
try
{
var x = cake.frosting.berries.loader;
...
}
catch (NullReferenceException ex)
{
// either one of cake, frosting, or berries was null
...
}
I personally wouldn't do this. It doesn't look nice, and since it uses exception handling, it probably also doesn't perform very well.
So is it possible using some extension method or would it be a language feature, [...]
This would almost certainly have to be a language feature, unless C# already had more sophisticated lazy evaluation, or unless you want to use reflection (which probably also isn't a good idea for reasons of performance and type-safety).
Since there's no way to simply pass cake.frosting.berries.loader
to a function (it would be evaluated and throw a null reference exception), you would have to implement a general look-up method in the following way: It takes in an objects and the names of properties to look up:
static object LookupProperty( object startingPoint, params string[] lookupChain )
{
// 1. if 'startingPoint' is null, return null, or throw an exception.
// 2. recursively look up one property/field after the other from 'lookupChain',
// using reflection.
// 3. if one lookup is not possible, return null, or throw an exception.
// 3. return the last property/field's value.
}
...
var x = LookupProperty( cake, "frosting", "berries", "loader" );
(Note: code edited.)
You quickly see several problems with such an approach. First, you don't get any type safety and possible boxing of property values of a simple type. Second, you can either return null
if something goes wrong, and you will have to check for this in your calling function, or you throw an exception, and you're back to where you started. Third, it might be slow. Fourth, it looks uglier than what you started with.
[...], or is it just a bad idea?
I'd either stay with:
if (cake != null && cake.frosting != null && ...) ...
or go with the above answer by Mehrdad Afshari.