Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.net get Properties using Reflection at Multilevel

Sorry if this is a duplicate. I searched and was not able to find an answer. How do I use reflection to get Values of Properties of class at multilevel?

I have a List of string that has some string values like this:

ClassNames =  {"FirstName", "LastName", "Location.City", "Location.State", "Location.Country", "PhoneNo"}

I have two classes

public class Details
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public Location Location { get; set; }
        public string PhoneNo { get; set; }
    }

public class Location
    {
        public long City { get; set; }
        public string State { get; set; }
        public string Country { get; set; }
    }

I used reflection and I am able to get the values of firstname, lastname and phone. But how do I get the values in the location class? It throws an Error. I change the List to just have Location / City . I am missing something. I dont want to do Multiple for loops as the level might drill down to n level. (4 max to be realistic)

foreach (string fieldname in ClassNames)
 {
 string fieldvalue = RestultDTO[indexValue]GetType().GetProperty(fieldname) ;
 }
like image 732
Night Monger Avatar asked Nov 16 '25 20:11

Night Monger


1 Answers

You'd have to get the Location instance first:

var s = "Location.City";
var sVals = s.Split('.');

// here [t] is the TypeInfo of [Details]
var l = t.GetProperty(sVals[0]);
        ^ gets the Location PropertyInfo (really only need to do this once

var val = l.GetProperty(sVals[1]).GetValue(l.GetValue(o));
          ^ gets the PropertyInfo for the property you're after (City in this case)
                                  ^ gets the actual value of that property
                                           ^ gets the value of Location for o where o is an instance of Details

If you're using a version before 4.5 you'll probably need to send in one additional parameter to the GetValue method - it can be , null both times because the properties aren't indexers.

like image 177
Mike Perrenoud Avatar answered Nov 19 '25 08:11

Mike Perrenoud