0

Using reflection I get a set of PropertyInfo:

var infos = typeof(T).GetProperties(.....)

My object (simplified)

Customer
     Dog   (class with field 'Name')
     Cow   (class with field 'Name')
     FName (string)

When I loop though the infos, I Console Write the Property's value. If the property is a class (Dog, Cow etc) and that class has a "Name" property, then I need to Write the "Name" value.

Basically how do I determine if the MemeberInfo is a class and has a property called "Name" and Write it out?

2 Answers 2

1

@Moho is right, but it doesn't explain how to write the actual name out which I think you want.

This will do it, assuming that your Customer object is in a variable called obj:

        foreach (var pi in typeof(T).GetProperties())
        {
            var propertyValue = pi.GetValue(obj); // This is the Dog or Cow object
            var pt = pi.PropertyType;

            var nameProperty = pt.GetProperty("Name");
            if (pt.IsClass && nameProperty != null)
            {
                var name = nameProperty.GetValue(propertyValue); // This pulls the name off of the Dog or Cow
                Console.WriteLine(name);
            }
        }
1
foreach( var pi in typeof( startingType ).GetProperties() )
{
    var pt = pi.PropertyType;

    if( pt.IsClass && null != pt.GetProperty( "Name" ) )
    {
        Console.WriteLine( pt.Name + " (class with field 'Name')" );
    }
}
2
  • This is wrong, it will output the Name property of the pt object not the property's value.
    – Ben Voigt
    Commented Feb 6, 2014 at 18:02
  • ah, i misunderstood, he wants the actual value of the property
    – Moho
    Commented Feb 6, 2014 at 18:05

Not the answer you're looking for? Browse other questions tagged or ask your own question.