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.cs207 chars9 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