I have a struct that has a ton of named bool members. (Please leave good practices and such out of consideration now for the sake of the example).
I want to randomly set these values to either true or false, just for testing purposes.
How can I do this through reflection?
This is what I have so far:
Random r = new Random();
foreach (var bool_field in state.GetType().GetFields().Where(x => x.GetType() == false.GetType()))
{
bool_field.SetValue(state, r.Next() % 2 == 0 ? true : false);
}
Unfortunately, it never enters the loop.
UPDATE 1:
Here is how the SystemState struct looks like, which is the type of the state variable. It is filled with bool auto properties.
public struct SystemState
{
...
public bool CanYouHelpMeOnThisOne { get; set; }
...
}
UPDATE 2:
The solution posted below seems nice, but it does not work. The reason is that SystemState is a struct not a class. Therefor it is a Value type not a Reference type, so calling the SetValue method has no effect. After changing SystemState to class, the below solution works perfectly.
Now is there any other way, to achieve this without changing SystemState to class?