Parsing a enumerator with a random to determine left or right by using a ternary operator c#

94 Views Asked by At

Hello stackoverflow community,

I'm working on a project and am stuck on the following. What I have is a public enum HorizontalDirection class that determines Left or Right. What I need to do is call random.Next(0, 2) with my ternary operator to determine if it is 0 move left else if 1 right. I have not had any luck with any of the following so far.

Enum.Parse(random.Next(0, 2) == 0 ? HorizontalDirection.Left : HorizontalDirection.Right);

(HorizontalDirection)random.Next(0, 2) == 0 ? HorizontalDirection.Left : HorizontalDirection.Right;

To the majority that are more experienced than I am I apologize for taking your time on something that might seem trivial to you. To me it's an opportunity to learn why my logic fails.

2

There are 2 best solutions below

3
On

You just need to do a random and cast it to enum:
This is because an int can be casted to an enum (as far as the int o is 0 or 1 !). (myEnum)0 will return the first value of myEnum and so on. Good luck on your project !

Random rd = new Random();
HorizontalDirection direction = (HorizontalDirection) rd.Next(2); 

And this is how it would look like with ternary operators:

Random rd = new Random();
var random = rd.Next(2);
HorizontalDirection direction = random == 0 ? HorizontalDirection.Left : TransactionState.Right;
1
On

Your second option works. Here's a working example.

var l = new List<HorizontalDirection>();

Random r = new Random();
for(int i = 0; i < 1000;i++)
{
    var d = r.Next(0, 2) == 0 ? HorizontalDirection.Left : HorizontalDirection.Right;
    l.Add(d);
}


Console.WriteLine($"lefts: {l.Count(d => d == HorizontalDirection.Left)}, rights: {l.Count(d => d == HorizontalDirection.Right)}");

Output

lefts: 468, rights: 532