Suppose that you have a class with various non-public fields, e.g., the class named ClassToTest
below servers as a good example.
1 2 3 4 5 6 7 8 9 |
|
And suppose that we desire to assign some value to the private variable m_somePrivateVar
, and the private property m_somePrivateProperty
. The approach is to iterate through the fields of the ClassToTest
type to find the desired field. If it is a variable we should type-cast it to FieldInfo
, and if it is a property we should type-cast it to PropertyInfo
. Then we should call the SetValue
method appropriately. This is shown below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
|
Here we have successfully assigned values to selected private fields of our class.