Change / Set private property with reflection in C#

C#Reflection

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

2
Sef Bkn [1]  •  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

Author

Created by coredev [37] Sep 29 '15

Share article

Do you know about

ReSharper?

Write an article