"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Set Property Values Dynamically in C# Using Reflection?

How Can I Set Property Values Dynamically in C# Using Reflection?

Posted on 2025-04-08
Browse:110

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:

  1. Get the PropertyInfo Object: Use Type.GetProperty to retrieve the PropertyInfo object associated with the property you want to modify. If the property is not public, you may need to specify additional binding flags, such as BindingFlags.NonPublic or BindingFlags.Instance.
  2. Invoke the SetValue Method: Once you have the PropertyInfo object, invoke its SetValue method to actually set the value of the property. This method takes two parameters: the object instance you want to modify and the new value to set.

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3