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

To get the val­ue of a pri­vate field of an instance in C#:

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

Sim­i­lar­ly, you can quite eas­i­ly retrieve the val­ue of a con­st or sta­t­ic field for a type, sim­ply replace BindingFlags.Instance with BindingFlags.Static and call Get­Val­ue with null:

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

Liked this post? Why not support me on Patreon and help me get rid of the ads!