Saw this a while back; it's simpler (dirty and wrong but... ):
public static T Get<T>(Func<T> getDelegate,
bool DefaultTOnNull = false, T defaultVal = null) where T : class
{
T result = null;
try
{
result = getDelegate();
}
catch (NullReferenceException) { }
catch (IndexOutOfRangeException) { }
catch (ArgumentOutOfRangeException) { }
return DefaultTOnNull ? result ?? default(T) : defaultVal == null ? result : defaultVal;
}
An example call would be:
NullHelper.Get( ()=>MyObject.MyProperty.MyLIstProperty[0].FirstName.ToString() );