Dereferencing a property

  • Thread starter Thread starter Max Sandman
  • Start date Start date
M

Max Sandman

Say I've got a control c = textBox1 and a string that is a property of
c, say string s = "Text". Is there a way in C# to use c and s to get
the contents of textbox1.Text?

sandman
 
Max,

Yes, you can use reflection to do this:

// Get the type of c first.
Type pobjTypeOfC = c.GetType();

// Now get the property on that type.
PropertyInfo pobjPropInfo = pobjTypeOfC.GetProperty(s);

// Now get the value for that property.
string pobjText = (string) pobjPropInfo.GetValue(c, null);

Basically, you are getting the type information for the instance of c in
the first line. Then, you are getting the property information in the
second, finally invoking the property in the third.

Hope this helps.
 
Hi Max,

You can do that with reflection:
textBox1.GetType().GetProperty( property_name ) give you a PropertyInfo
instance ( or null if the property does not exist ), you can then call
GetValue to get the value of it, to GetValue you have to pass the original
instance this property came from.

Hope this help,
 
Back
Top