Home >Backend Development >C++ >How Can I Set Property Values Dynamically in C# Using Reflection?
Setting Property Values Using Reflection
It is possible to dynamically set the value of a property using reflection in C#. This allows you to modify an object's property at runtime, regardless of its accessibility or visibility.
To set a property value using reflection, follow these steps:
Here's an example that demonstrates how to use reflection to set the firstName property of a Person class:
using System; using System.Reflection; class Person { public string FirstName { get; set; } } class Test { static void Main(string[] args) { // Create an instance of the Person class Person p = new Person(); // Get the PropertyInfo object for the FirstName property var property = typeof(Person).GetProperty("FirstName"); // Set the value of the FirstName property using reflection property.SetValue(p, "John", null); // Print the value of the FirstName property Console.WriteLine(p.FirstName); // John } }
In this example, the property variable holds a reference to the FirstName property of the Person class. The SetValue method is invoked with the p instance and the string value "John" to set the property's value dynamically.
The above is the detailed content of How Can I Set Property Values Dynamically in C# Using Reflection?. For more information, please follow other related articles on the PHP Chinese website!