How to get Random Results of an Enum? [C#]

Shaitan00

Junior Contributor
Joined
Aug 11, 2003
Messages
358
Location
Hell
I have a variable of type "MoveDirection" that is currently used like this: MoveDirection direction = MoveDirection.Right;
However, instead of always going right (MoveDirection.Right) I wanted to make it RANDOM, so that "direction" could be any of the four possible results in the enum MoveDirection

Given the following Enum:
Code:
public enum MoveDirection
{
	Right,
	Up,
	Down,
	Left
}

I need a way to generate a Random value of the enum MoveDirection, I thought of using Rand but am unable to generate anything other then just random numbers and not random enums of type MoveDirection.
Any ideas, hints, and help would be greatly appreciated, thanks
 
Simply put, cast a randomly generated number to a MoveDirection value.
C#:
Random rand = new Random();
// You need to crop the range to 0...3 since your enum's
// integer values are 0, 1, 2, and 3.
MoveDirection whichWayToGo = (MoveDirection)(rand.Next() % 4);
MessageBox.Show(whichWayToGo.ToString());
 
Back
Top