Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Using Reflection to Get a Generic Object's (and its Nested Objects) Properties

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.

like image 242
Jimbo Avatar asked May 26 '10 09:05

Jimbo


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is C in C language?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

Is C language easy?

Compared to other languages—like Java, PHP, or C#—C is a relatively simple language to learn for anyone just starting to learn computer programming because of its limited number of keywords.


1 Answers

Here's a simple method that uses recursion to solve your problem. It allows you to traverse an object graph by passing a "dotted" property name. It works with properties as well as fields.

static class PropertyInspector 
{
    public static object GetObjectProperty(object item,string property)
    {
        if (item == null)
            return null;

        int dotIdx = property.IndexOf('.');

        if (dotIdx > 0)
        {
            object obj = GetObjectProperty(item,property.Substring(0,dotIdx));

            return GetObjectProperty(obj,property.Substring(dotIdx+1));
        }

        PropertyInfo propInfo = null;
        Type objectType = item.GetType();

        while (propInfo == null && objectType != null)
        {
            propInfo = objectType.GetProperty(property, 
                      BindingFlags.Public 
                    | BindingFlags.Instance 
                    | BindingFlags.DeclaredOnly);

            objectType = objectType.BaseType;
        }

        if (propInfo != null)
            return propInfo.GetValue(item, null);

        FieldInfo fieldInfo = item.GetType().GetField(property, 
                      BindingFlags.Public | BindingFlags.Instance);

        if (fieldInfo != null)
            return fieldInfo.GetValue(item);

        return null;
    }
}

Example:

class Person
{
   public string Name { get; set; }
   public City City { get; set; }
}

class City
{
   public string Name { get; set; }
   public string ZipCode { get; set; }
}

Person person = GetPerson(id);

Console.WriteLine("Person name = {0}", 
      PropertyInspector.GetObjectProperty(person,"Name"));

Console.WriteLine("Person city = {0}",
      PropertyInspector.GetObjectProperty(person,"City.Name"));
like image 58
Philippe Leybaert Avatar answered Oct 11 '22 13:10

Philippe Leybaert