34

I know the name of a property in my C# class. Is it possible to use reflection to set the value of this property?

For example, say I know the name of a property is string propertyName = "first_name";. And there actaully exists a property called first_name. Can I set it using this string?

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
user489041
  • 27,916
  • 55
  • 135
  • 204

1 Answers1

77

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194