C# Reflection Question

Posted by Jimbo on Stack Overflow See other posts from Stack Overflow or by Jimbo
Published on 2010-05-26T09:39:51Z Indexed on 2010/05/26 9:41 UTC
Read the original article Hit count: 210

Filed under:
|
|
|
|

This is a scenario created to help understand what Im trying to achieve.

I am trying to create a method that returns the specified property of a generic object

e.g.

public object getValue<TModel>(TModel item, string propertyName) where TModel : class{
    PropertyInfo p = typeof(TModel).GetProperty(propertyName);
    return p.GetValue(item, null);
}

The code above works fine if you're looking for a property on the TModel item e.g.

string customerName = getValue<Customer>(customer, "name");

However, if you want to find out what the customer's group's name is, it becomes a problem: e.g.

string customerGroupName = getValue<Customer>(customer, "Group.name");

Hoping someone can give me some insight on this way out scenario - thanks.

© Stack Overflow or respective owner

Related posts about c#

Related posts about generics