I have a list of static variables in a static class.
namespace Test
{
public static class Numbers
{
public static readonly int One = 1;
public static readonly int Five = 5;
public static readonly int Ten = 10;
public static readonly int Eleven = 11;
public static readonly int Fifteen= 15;
}
}
And I want to randomly select a variable in the class. How can I achieve this?
int randomVariable = SomeFunction(Numbers);
Use reflection:
FieldInfo[] fields= typeof(Numbers).GetFields(
BindingFlags.Public | BindingFlags.Static);
var rnd = new Random();
int randomVariable = (int) fields[rnd.Next(fields.Length)].GetValue(null);
Better solution without reflection:
Create an array of integers Numbers as a static property and initialize it to the values in the class Numbers:
Numbers = fields.Select(f => (int)f.GetValue()).ToArray(); //int[]
Then when getting a random value:
int randomVariable = Numbers[rnd.Next(Numbers.Length)];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With