7

Possible Duplicate:
How can I read the properties of a C# class dynamically?

I have to get values of class members using strings of their names only. I think I have to use Reflection but I am not realy sure how to. Can you help me?

Community
  • 1
  • 1
kali
  • 109
  • 1
  • 2
  • 9
  • 3
    I have one question before I can help - What are you talking about? Can you post an example of what you are trying to do? – JonH Jan 03 '13 at 13:51
  • Yep. We'll vote to close the question if you don't really provide any example of what you need. – gideon Jan 03 '13 at 13:52

2 Answers2

11
MemberInfo member = typeof(MyClass).GetMember("membername");

GetMember reference.

If you know type of member you're looking for, you can use .GetMethod, .GetField, .GetProperty, etc.

If you don't know the type you are working with:

var myobject = someobject;
string membername = "somemember";
MemberInfo member = myobject.GetType().GetMember(membername);

Different member types have different means to getting the value. For a property you would do:

var myobject = someobject;
string propertyname = "somemember";
PropertyInfo property = myobject.GetType().GetProperty(membername);
object value = property.GetValue(myobject, null);
Paul Fleming
  • 24,238
  • 8
  • 76
  • 113
8
public class Foo
{
  public string A { get; set; }
}
public class Example
{
  public void GetPropertyValueExample()
  {
    Foo f = new Foo();
    f.A = "Example";
    var val = f.GetType().GetProperty("A").GetValue(f, null);
  }
}
LukeHennerley
  • 6,344
  • 1
  • 32
  • 50