update a property's value using reflection in csharp

Here's an example of how to update a property's value using reflection in C#:

main.cs
// assume we have a class Person with a property Name
public class Person {
    public string Name { get; set; }
}

// create an instance of Person
var person = new Person { Name = "John" };

// get the type of person using reflection
var type = person.GetType();

// get the Name property using reflection
var nameProperty = type.GetProperty("Name");

// update the value of the Name property using SetValue method
nameProperty.SetValue(person, "Jane");

// verify the value has been updated
Console.WriteLine(person.Name); // output: "Jane"
543 chars
20 lines

In the above example, we first create an instance of the Person class and set the initial value of the Name property to "John". We then use reflection to get the type of the person variable using the GetType() method. Next, we use the GetProperty() method to get a reference to the Name property of the Person class. Finally, we use the SetValue() method to update the value of the Name property to "Jane". We can then verify that the value has been updated by printing it to the console using Console.WriteLine().

gistlibby LogSnag