get a random element from an array in csharp

To get a random element from an array in C#, you can use the Random class to generate a random index within the range of the array, and then access the element at that index. Here's an example:

main.cs
int[] myArray = {1, 2, 3, 4, 5};

Random rnd = new Random();
int randomIndex = rnd.Next(0, myArray.Length);

int randomElement = myArray[randomIndex];

Console.WriteLine("Random element: " + randomElement);
207 chars
9 lines

In the code above, we first define an array called "myArray" with some integer elements. Then, we create an instance of the Random class, which we will use to generate a random index. Calling the Next method of the Random class with 2 arguments (the lower and upper bounds of the range), returns a random integer in that range.

We then use that random index to access an element in the array and store it in randomElement. Finally, we output the randomly selected element to the console.

gistlibby LogSnag