Click here to Skip to main content
11,647,748 members (69,431 online)
Click here to Skip to main content

Get Nested Property value using reflection and Linq.Expression

, 8 Apr 2011 CPOL 7.4K 2
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)

Share

About the Author

cechode
United States United States
No Biography provided

You may also be interested in...

Comments and Discussions

 
GeneralRe: :) Pin
Sandeep Mewara8-Apr-11 9:07
mvpSandeep Mewara8-Apr-11 9:07 
GeneralRe: actually that's probably a great rule ! Pin
cechode8-Apr-11 9:03
membercechode8-Apr-11 9:03 
GeneralRe: It will take 5 people approval to get published. (New rule o... Pin
Sandeep Mewara8-Apr-11 9:02
mvpSandeep Mewara8-Apr-11 9:02 
GeneralRe: no approval :( ( heh ) Pin
cechode8-Apr-11 8:56
membercechode8-Apr-11 8:56 
GeneralRe: Ok! :) Pin
Sandeep Mewara8-Apr-11 8:23
mvpSandeep Mewara8-Apr-11 8:23 
GeneralReason for my vote of 5 ghghgh Pin
DEEPAK BHAKTA19-Apr-11 1:25
memberDEEPAK BHAKTA19-Apr-11 1:25 
GeneralReason for my vote of 1 ghghgh Pin
DEEPAK BHAKTA19-Apr-11 1:25
memberDEEPAK BHAKTA19-Apr-11 1:25 
GeneralReason for my vote of 4 ghghgh Pin
DEEPAK BHAKTA19-Apr-11 1:24
memberDEEPAK BHAKTA19-Apr-11 1:24 
GeneralReason for my vote of 2 ghghgh Pin
DEEPAK BHAKTA19-Apr-11 1:24
memberDEEPAK 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
mvpSandeep Mewara8-Apr-11 8:03 
GeneralRe: "Dirty and wrong" in this context pertains to whether or not... Pin
cechode8-Apr-11 8:12
membercechode8-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 | Terms of Use | Mobile
Web04 | 2.8.150804.3 | Last Updated 8 Apr 2011
Article Copyright 2011 by cechode
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid