I need to get the Name and Value of all properties of each object. Some of them are reference type so if I get the following objects:
public class Artist {
public int Id { get; set; }
public string Name { get; set; }
}
public class Album {
public string AlbumId { get; set; }
public string Name { get; set; }
public Artist AlbumArtist { get; set; }
}
When getting the properties from the Album
object I would need also to get the values of properties AlbumArtist.Id
and AlbumArtist.Name
which are nested.
I have the following code so far, but it triggers the System.Reflection.TargetException when trying to get the value of the nested ones.
var valueNames = new Dictionary<string, string>();
foreach (var property in row.GetType().GetProperties())
{
if (property.PropertyType.Namespace.Contains("ARS.Box"))
{
foreach (var subProperty in property.PropertyType.GetProperties())
{
if(subProperty.GetValue(property, null) != null)
valueNames.Add(subProperty.Name, subProperty.GetValue(property, null).ToString());
}
}
else
{
var value = property.GetValue(row, null);
valueNames.Add(property.Name, value == null ? "" : value.ToString());
}
}
So in the If
statement I just check if the property is under the namespace of my reference types, if it is I should get all the nested properties values but that's where the exception is raised.
Thanks in advance for the help..