faqts : Computers : Programming : Languages : C# : .NET Framework : System : Reflection

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

24 of 25 people (96%) answered Yes
Recently 9 of 10 people (90%) answered Yes

Entry

How can I get and set an object property by name?
I have a property name in a variable, how can I get or set that property?

Apr 27th, 2002 16:33
Nathan Wallace,


You can use Reflection to get and set a property by name.  Here is 
some example code: 
  // obj is the object to set the property on (can be this)
  // newValue is the new property value
  string propertyName = "PropertyName";
  System.Reflection.PropertyInfo property;
  property = Type("MyObject").GetProperty(propertyName);
  property.SetValue(obj, newValue, null);
You can read more about the property info class here:
  http://msdn.microsoft.com/library/default.asp?url=/library/en-
us/cpref/html/frlrfsystemreflectionpropertyinfoclasstopic.asp