How to Use PropertyInfo in C#

PropertyInfo is a class in reflection used to retrieve and modify information about properties.

  1. Obtain attribute information:

Obtain the PropertyInfo object of a property with a specified name using the Type.GetProperty method. For example:

Type type = typeof(MyClass);
PropertyInfo propertyInfo = type.GetProperty("MyProperty");
  1. Retrieve attribute value:

Use the PropertyInfo.GetValue method to access the value of a property. You must provide the object instance to which the property belongs as a parameter. For example:

object propertyValue = propertyInfo.GetValue(myObject);
  1. Set attribute value:

Use the PropertyInfo.SetValue method to set the value of a property. Provide the object instance to which the property belongs and the value to be set as parameters. For example:

propertyInfo.SetValue(myObject, newValue);
  1. Obtain additional information about the property.

One can utilize other methods and properties provided by the PropertyInfo object, such as PropertyInfo.Name to obtain the name of the property and PropertyInfo.PropertyType to obtain the type of the property. For example:

string propertyName = propertyInfo.Name;
Type propertyType = propertyInfo.PropertyType;

These are simple uses of PropertyInfo, for more advanced uses please refer to the MSDN documentation or other relevant resources.

bannerAds