Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get class members values having string of their names? [duplicate]

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?

like image 303
kali Avatar asked Jan 03 '13 13:01

kali


2 Answers

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);
like image 160
Paul Fleming Avatar answered Nov 03 '22 19:11

Paul Fleming


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);
  }
}
like image 39
LukeHennerley Avatar answered Nov 03 '22 19:11

LukeHennerley