Using Reflection to get property from field

I have these classes:

public class Foo
    public Bar bar;

public class Bar
    public List<int> Something { get; set; }
    public string Else { get; set; }

I have a lot of classes like Foo. They all contain exactly one field. This field, Bar in my example, will be a different type of object every time, it doesn't have to be of type Bar. Whatever object it is (Bar or otherwise), this field will always be an object that has two properties, Something and Else.

My challenge: given any object that's like Foo (with one Field that holds two properties), get the value of the two properties. Given this method:

public void DoStuff(object myObject)
    var asdf = myObject.GetType().GetFields().First();

I can get the FieldInfo for Bar. What I'm looking for is the values of Something and Else. The names of these properties never change. Whatever the type is of the Field, it will always have two properties named Something and Else that will be of the same type.

Sadly, my problem involves auto generated code, and there are no shared interfaces or base types I can easily use.

Read more here:

Content Attribution

This content was originally published by yesman at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: