Change / Set private property with reflection in C#

A problem that can occur when creating unit tests is that you’ve got a private set:er for a property that you need to write data to in order to create a testable entity. This is how you can write to the private property by using Reflection:

//Example class
public class Person {
    public string Name { get; private set; }

var person = new Person();

//Cannot do this due to the private set:er:
//person.Name = "Foo";

//Set value by using Reflection:
person.GetType().GetProperty("Name").SetValue(person, "Foo", null);

NB: do NOT use this outside of unit testing. There is a reason for that set:er to be private.


Posted in C#