Namespace: System.Reflection
Represents a property on a type and provides methods for getting or setting the property's value. This is an abstract class that is implemented by specific property types.
Object
> MemberInfo
> PropertyInfo
Use the members of the PropertyInfo
class to get information about a property, such as its name, type, and accessibility. You can also use it to get or set the value of the property on an instance of the class.
To get a PropertyInfo
object, you can use methods such as Type.GetProperty
or Type.GetProperties
.
Name | Description |
---|---|
GetValue |
Gets the value of the property on a specified object.
Parameters:
|
SetValue |
Sets the value of the property on a specified object.
Parameters:
|
GetAccessors |
Gets the public get accessor of the property.
Returns: A MethodInfo object representing the public get accessor, or null if the accessor is not public or does not exist.
|
SetAccessors |
Gets the public set accessor of the property.
Returns: A MethodInfo object representing the public set accessor, or null if the accessor is not public or does not exist.
|
Name | Type | Description |
---|---|---|
CanRead | bool |
Indicates whether the property can be read. |
CanWrite | bool |
Indicates whether the property can be written to. |
PropertyType | Type |
Gets the type of the property. |
IsSpecialName | bool |
Indicates whether the property's name is special. |
GetAccessors | MethodInfo[] |
Gets the public and private accessors for the property. |
SetAccessors | MethodInfo[] |
Gets the public and private set accessors for the property. |
using System;
using System.Reflection;
public class Example
{
public string MyProperty { get; set; } = "Initial Value";
public static void Main(string[] args)
{
Example instance = new Example();
Type type = typeof(Example);
// Get the PropertyInfo for "MyProperty"
PropertyInfo propertyInfo = type.GetProperty("MyProperty");
if (propertyInfo != null)
{
// Get the current value
object currentValue = propertyInfo.GetValue(instance);
Console.WriteLine($"Current Value: {currentValue}"); // Output: Current Value: Initial Value
// Set a new value
string newValue = "Updated Value";
propertyInfo.SetValue(instance, newValue);
// Get the updated value
object updatedValue = propertyInfo.GetValue(instance);
Console.WriteLine($"Updated Value: {updatedValue}"); // Output: Updated Value: Updated Value
// Get property type
Console.WriteLine($"Property Type: {propertyInfo.PropertyType.Name}"); // Output: Property Type: String
}
else
{
Console.WriteLine("Property 'MyProperty' not found.");
}
}
}