Reputation: 41
I am working with a method that takes an anonymous object and a string, and then compares the string to the object property names.
In this example the object is a model that contains basic properties and a custom class property:
Model:
class MyClass
{
public string Name { get; set; }
public AddressClass Address { get; set; }
}
public class AddressClass
{
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
}
The method (the MyClass model is being passed):
protected string GetPropertyName(object model, string propertyName)
{
var propertyInfo = model.GetType().GetProperties().FirstOrDefault(pi => pi.Name == propertyName);
return propertyInfo;
}
This code is working and returning 'Name' where the string is equal to 'Name'. But not working for 'AddressLine1' or 'AddressLine2' properties when the string is equal to those values. Instead it returns Null.
In this example is it possible to reach inside the model object, to compare the string, without specifying that model type in the method?
Thanks
Upvotes: 1
Views: 55
Reputation: 153
I'm a little confused what you need this for. Having the name of a property and an unknown model seems rather weird.
In any case, you can just loop through the properties and their properties. I've done it below using recursion. If you need the value of the property you need to change a few things.
protected string GetPropertyName(object model, string propertyName)
{
var propInfo = model as PropertyInfo;
var props = propInfo != null ? propInfo.PropertyType.GetProperties() : model.GetType().GetProperties();
foreach (var prop in props)
{
if (prop.Name == propertyName)
return prop.Name;
var subProb = GetPropertyName(prop, propertyName);
if (subProb != null)
return subProb;
}
return null;
}
Upvotes: 0