How to use PropertyInfo in C#?
In C#, PropertyInfo is a class used for getting and setting properties. You can use the following method to utilize PropertyInfo:
- To get the type of a property: You can use the PropertyType property of PropertyInfo to obtain the type of a property. For example, if there is a property named “Name,” you can use the following code to get the type of the property:
PropertyInfo propertyInfo = typeof(ExampleClass).GetProperty("Name");
Type propertyType = propertyInfo.PropertyType;
- To obtain the value of a property, you can use the GetValue method of PropertyInfo. You need to provide an object instance as a parameter to indicate from which object to get the property value. For example:
ExampleClass example = new ExampleClass();
example.Name = "John";
PropertyInfo propertyInfo = typeof(ExampleClass).GetProperty("Name");
object propertyValue = propertyInfo.GetValue(example);
- Setting the value of a property: You can use the SetValue method of PropertyInfo to set the value of a property. You need to provide an object instance and the value to be set as parameters. For example:
ExampleClass example = new ExampleClass();
PropertyInfo propertyInfo = typeof(ExampleClass).GetProperty("Name");
propertyInfo.SetValue(example, "John");
These are some of the basic usages of PropertyInfo. More advanced operations can also be performed using other methods and properties, such as fetching and setting the access modifiers and attributes of the property.