You're obviously looking for the Nullable Monad:
string result = new A().PropertyB.PropertyC.Value;
becomes
string result = from a in new A()
from b in a.PropertyB
from c in b.PropertyC
select c.Value;
This returns null
, if any of the nullable properties are null; otherwise, the value of Value
.
class A { public B PropertyB { get; set; } }
class B { public C PropertyC { get; set; } }
class C { public string Value { get; set; } }
LINQ extension methods:
public static class NullableExtensions
{
public static TResult SelectMany<TOuter, TInner, TResult>(
this TOuter source,
Func<TOuter, TInner> innerSelector,
Func<TOuter, TInner, TResult> resultSelector)
where TOuter : class
where TInner : class
where TResult : class
{
if (source == null) return null;
TInner inner = innerSelector(source);
if (inner == null) return null;
return resultSelector(source, inner);
}
}