Click here to Skip to main content
Click here to Skip to main content
Alternative Tip

Get Nested Property value using reflection and Linq.Expression

, 8 Apr 2011
Rate this:
Please Sign up or sign in to vote.
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... ):
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
No Biography provided

Comments and Discussions

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

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

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

| Advertise | Privacy | Mobile
Web04 | 2.8.140721.1 | Last Updated 8 Apr 2011
Article Copyright 2011 by cechode
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid