In this post we will learn how to “select random string from an array in C#”. We have the option to utilize the random number generator to select a random element from given array. The subsequent code snippet contains an array of student’s names (strings). We can select a random student by generating a random number that is smaller than the quantity of elements in the array and utilize the random index to select a random writer name within the string.

So, how to do this? The Random.Next() function produces a random whole number and by specifying the maximum size of the array, ensures that the generated number will not exceed the number of elements in the array.

       static void Main(string[] args)
         //let's create Students Array
         string[] students = { "Mukesh", "Ravi", "David", "Peter","Smith", "Henry", "Raj k", "Mark Smith","Tracey", "Thomson" };
            // Let's Create a Random number  using Random class object
            Random rand = new Random();
            // Lets Generate a random  number which is less than the size of the our array.
            int index = rand.Next(students.Length);
            Console.WriteLine($"Randomly Selected Student is {students[index]}");

Random String Output:

Random -

Hence using above example, we discussed how to select a random string from an array of strings. You can also check same in JavaScript here and can Visit our website’s C# Section for more such information.

You may like:

Leave a Reply

Your email address will not be published. Required fields are marked *

Explore More

Working With File Class In C#

In C#, ‘File’ class provides many static methods for moving, copying, and deleting files. These Static methods involve moving a file and copying and deleting a file also. Let’s check

How to Read a Text File in C#

In C# ‘File’ class provides static methods to read given text file data. The File.ReadAllText() method opens a text file, reads all the text present in the file into a

C# | How to use Interface references

In C#, you’re permitted to make a reference variable of an interface type or in other words, you’re permitted to form an interface reference variable. Such kind of variable can