Click here to Skip to main content
15,884,986 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have nested class which has two properties. 
I need to get value of one the of the nested class along with main class.

		foreach (var row in reportRowList)
            {
                var k = row;
                List<object> dataRow = new List<object>();
                properties.ForEach(p =>
                {

                    dataRow.Add(p.GetValue(row));
                   
                });

                table.Rows.Add(dataRow.ToArray());
            }
			
			Below is my code. How do i extend GetValue Method of PropertyInfo to retrieve nested object properties 


What I have tried:

public static Object GetPropValue(this Object obj, String propName)
       {
           string[] nameParts = propName.Split('.');
           if (nameParts.Length == 1)
           {
               return obj.GetType().GetProperty(propName).GetValue(obj, null);
           }

           foreach (String part in nameParts)
           {
               if (obj == null) { return null; }

               Type type = obj.GetType();
               PropertyInfo info = type.GetProperty(part);
               if (info == null) { return null; }

               obj = info.GetValue(obj, null);
           }
           return obj;
       }
Posted
Updated 28-May-19 5:45am
Comments
BillWoodruff 28-May-19 23:04pm    
First, why are you using reflection ?
istudent 29-May-19 5:59am    
For a common code to create excel in app.

1 solution

obj = info.GetValue(obj, null);


At this point, you call GetPropValue() to get the "nested class properties"; insuring, of course, you only "dive down" 1 extra level in this case.

How you supply your target properties for the nested class is another matter: 2 lists / strings?
 
Share this answer
 
Comments
istudent 28-May-19 12:26pm    
If you looked at the code, not the one I tried, I am iterating over the properties I retrieved for the row object and retrieving the value from the object and adding them in a data row in table. What I have tried was I got that from Google search, which always have object name and return null
istudent 29-May-19 6:48am    
I resolve my problem by creating atother class and map all the properties required from nested class and the things done. But I still like to learn how can we do it.. Without creating another class

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900