Hi have been given a task that I am struggling with. I need to assign a random enum
to a property. The code I have is this.
public enum PegColour
{
Red, Green, Blue, Yellow, Black, White
}
And other class which looks like this
public class PegContainer
{
/// <summary>
/// Dfines the colour of the first peg
/// </summary>
public Peg Colour1 { get; set; }
/// <summary>
/// Dfines the colour of the secod peg
/// </summary>
public Peg Colour2 { get; set; }
/// <summary>
/// Dfines the colour of the third peg
/// </summary>
public Peg Colour3 { get; set; }
/// <summary>
/// Dfines the colour of the forth peg
/// </summary>
public Peg Colour4 { get; set; }
public void GeneratePegs()
{
}
}
my GeneratePegs()
method should, each time it is called randomly assign one of the enum
colours to one of the properties (Colour1
, Colour2
etc.) to complicate matters I need the randomizer to ignore Black
and White
.
Enums are just integers and therefore integers can be cast to an enum. I would do this:
Black and White will never get selected because it only picks randomly from the first 4 colors. As long as you add pegs BEFORE the black and white pegs, this code should work every time, even if you add or remove pegs from the enumeration. So if you wanted to add new colors, you'd just change
PegColour
to something like this:You wouldn't need to change anything else!
So your
GeneratePegs()
method should just look like this: