Click here to Skip to main content
Click here to Skip to main content

Get Nested Property value using reflection and Linq.Expression

By , 8 Apr 2011
 
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() );

License

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

About the Author

cechode
United States United States
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralRe: :)mvpSandeep Mewara8 Apr '11 - 9:07 
GeneralRe: actually that's probably a great rule ! membercechode8 Apr '11 - 9:03 
GeneralRe: It will take 5 people approval to get published. (New rule o...mvpSandeep Mewara8 Apr '11 - 9:02 
GeneralRe: no approval :( ( heh )membercechode8 Apr '11 - 8:56 
GeneralRe: Ok! :)mvpSandeep Mewara8 Apr '11 - 8:23 
GeneralReason for my vote of 5 ghghghmemberDEEPAK BHAKTA19 Apr '11 - 1:25 
GeneralReason for my vote of 1 ghghghmemberDEEPAK BHAKTA19 Apr '11 - 1:25 
GeneralReason for my vote of 4 ghghghmemberDEEPAK BHAKTA19 Apr '11 - 1:24 
GeneralReason for my vote of 2 ghghghmemberDEEPAK BHAKTA19 Apr '11 - 1:24 
GeneralWhen it's dirty and wrong both, then why suggest it to someo...mvpSandeep Mewara8 Apr '11 - 8:03 
GeneralRe: "Dirty and wrong" in this context pertains to whether or not...membercechode8 Apr '11 - 8:12 

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

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130516.1 | Last Updated 8 Apr 2011
Article Copyright 2011 by cechode
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid