Click here to Skip to main content
15,867,308 members
Articles / Web Development / ASP.NET
Alternative
Tip/Trick

Get Nested Property value using reflection and Linq.Expression

Rate me:
Please Sign up or sign in to vote.
4.67/5 (3 votes)
8 Apr 2011CPOL 20.7K   2   11
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)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralRe: :) Pin
Sandeep Mewara8-Apr-11 9:07
mveSandeep Mewara8-Apr-11 9:07 
GeneralRe: actually that's probably a great rule ! Pin
cechode8-Apr-11 9:03
cechode8-Apr-11 9:03 
GeneralRe: It will take 5 people approval to get published. (New rule o... Pin
Sandeep Mewara8-Apr-11 9:02
mveSandeep Mewara8-Apr-11 9:02 
GeneralRe: no approval :( ( heh ) Pin
cechode8-Apr-11 8:56
cechode8-Apr-11 8:56 
GeneralRe: Ok! :) Pin
Sandeep Mewara8-Apr-11 8:23
mveSandeep Mewara8-Apr-11 8:23 
GeneralReason for my vote of 5 ghghgh Pin
DEEPAK BHAKTA19-Apr-11 1:25
DEEPAK BHAKTA19-Apr-11 1:25 
GeneralReason for my vote of 1 ghghgh Pin
DEEPAK BHAKTA19-Apr-11 1:25
DEEPAK BHAKTA19-Apr-11 1:25 
GeneralReason for my vote of 4 ghghgh Pin
DEEPAK BHAKTA19-Apr-11 1:24
DEEPAK BHAKTA19-Apr-11 1:24 
GeneralReason for my vote of 2 ghghgh Pin
DEEPAK BHAKTA19-Apr-11 1:24
DEEPAK BHAKTA19-Apr-11 1:24 
GeneralWhen it's dirty and wrong both, then why suggest it to someo... Pin
Sandeep Mewara8-Apr-11 8:03
mveSandeep Mewara8-Apr-11 8:03 
GeneralRe: "Dirty and wrong" in this context pertains to whether or not... Pin
cechode8-Apr-11 8:12
cechode8-Apr-11 8:12 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.