Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Get Nested Property value using reflection and Linq.Expression

4.67/5 (3 votes)
8 Apr 2011CPOL 22.5K  
Saw this a while back; it's simpler (dirty and wrong but... ):public static T Get(Func getDelegate, bool DefaultTOnNull = false, T defaultVal = null) where T : class{ T result = null; try { result = getDelegate(); } catch...
Saw this a while back; it's simpler (dirty and wrong but... ):
C#
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:
C#
NullHelper.Get( ()=>MyObject.MyProperty.MyLIstProperty[0].FirstName.ToString() );

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)