Not sure if this is the best approach, but I saw it in a CodeProject post and thought it might be a useful approach.
This is a monadic solution using the "With" extension method:
public static TResult With<TInput, TResult>(this TInput o,
Func<TInput, TResult> evaluator)
where TResult : class where TInput : class
{
if (o == null) return null;
return evaluator(o);
}
and return extension method:
public static TResult Return<TInput,TResult>(this TInput o,
Func<TInput, TResult> evaluator, TResult failureValue) where TInput: class
{
if (o == null) return failureValue;
return evaluator(o);
}
, :
var myElement = element.With(x => x.Element("FooElement")).Return(x => x.Attribute("FooAttribute").Value, "MyDefaultValue")
, , , , IMO
CodeProject - Maybe