Can I set a property value with Reflection?

Yes, you can use reflection – just fetch it with Type.GetProperty (specifying binding flags if necessary), then call SetValue appropriately. Sample:

using System;

class Person
{
    public string Name { get; set; }
}

class Test
{
    static void Main(string[] arg)
    {
        Person p = new Person();
        var property = typeof(Person).GetProperty("Name");
        property.SetValue(p, "Jon", null);
        Console.WriteLine(p.Name); // Jon
    }
}

If it’s not a public property, you’ll need to specify BindingFlags.NonPublic | BindingFlags.Instance in the GetProperty call.

Leave a Comment