Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Choose a random static variable from a static class

Tags:

c#

.net

static

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);
like image 378
Ramesh Durai Avatar asked Jan 21 '26 18:01

Ramesh Durai


1 Answers

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)];
like image 157
Ahmed KRAIEM Avatar answered Jan 23 '26 07:01

Ahmed KRAIEM