Search code examples
c#randomenumsenum-flags

Random value from c# enum variable


Is there an easy way for me to select a random bit value from my enum variable?
For example:

[System.Flags]
public enum Direction{
    None = 0,
    Up = 1,
    Down = 2, 
    Left = 4, 
    Right = 8,
    All = ~None
}

public Direction someDir = Direction.Up | Direction.Down;

I would want to select a random positive bit value from someDir so that I could only have Direction.Up or Direction.Down?


Solution

  • You should use an array:

    Direction validDirections = new[] { Direction.Up, Direction.Down };
    

    and then:

    Random rnd = new Random();
    Direction selectedDirection = validDirections[rnd.Next(validDirections.Length)];
    

    (remember to reuse the same Random rnd and not recreate it every time)

    If you really really want to have a single Direction variable, then you could split it to a List<Direction>:

    Direction someDir = Direction.Up | Direction.Down;
    
    var someDir2 = new List<Direction>();
    
    foreach (Direction dir in Enum.GetValues(typeof(Direction)))
    {
        if (someDir.HasFlag(dir))
        {
            someDir2.Add(dir);
        }
    }
    
    Random rnd = new Random();
    Direction selectedDirection = someDir2[rnd.Next(someDir2.Count)];
    

    (see Most efficient way to parse a flagged enum to a list and the various comments about using HasFlag)