Change / Set private property with reflection in C#


Please contribute by voting. Thanks!
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.

Article created: Sep 29 '15. Edited Sep 29 '15.

1 Comment

Sef Bkn [2]  •  Nov 25 '15  •   •  Reply

Don't do this in unit testing. Sure, you can but you really shouldn't. If Name has a private setter, and you have access to the code for that class, then it should be set inside the class it belongs.

Instead, identify where the property is being set and perform assignment there. If the name is coming from a database or file, for example, then inject that dependency and mock the part of that dependency that returns the name.

Or... mock the object.

Let the class worry about its internals. Setting the name could trigger some other processes to run. Purely as a demonstration for reflection, however, no problem.


Your comment

You need to sign up / log in to comment this article


Created by coredev [38] Sep 29 '15

Share article

Do you know about


Write an article