How to get private, constant or static value of a field with reflection

To get the value of a private field of an instance in C#:

var actualNumberOfWinners =
        .GetField("_numberOfWinners", BindingFlags.NonPublic | BindingFlags.Instance)

Similarly, you can quite easily retrieve the value of a const or static field for a type, simply replace BindingFlags.Instance with BindingFlags.Static and call GetValue with null:

var constNumberOfWinners =
        .GetField("DefaultNumberOfWinners", BindingFlags.NonPublic | BindingFlags.Static)

Subscribe to my newsletter and get new contents delivered straight to your inbox :-)