Getting and setting properties

suggest change

Basic usage:

PropertyInfo prop = myInstance.GetType().GetProperty("myProperty");
// get the value myInstance.myProperty
object value = prop.GetValue(myInstance);

int newValue = 1;
// set the value myInstance.myProperty to newValue
prop.SetValue(myInstance, newValue);

A read-only automatically implemented property can be set through its compiler-generated backing field. For a property named myProperty, that field is <myProperty>k__BackingField:

// get backing field info
FieldInfo fieldInfo = myInstance.GetType()
    .GetField("<myProperty>k__BackingField", BindingFlags.Instance | BindingFlags.NonPublic);

int newValue = 1;
// set the value of myInstance.myProperty backing field to newValue
fieldInfo.SetValue(myInstance, newValue);

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents