Select Random String From An Array In .NET Core and C#

How to select a random string from an array of strings?

This article demonstrates how to pick a random string from an array of strings.

We can use the random number generator to pick a random item from an array. The following code snippet has an array of author names (strings). We can pick a random author by generating a random number that is less than the number of items in the array and use the random index to pick a random author name in the string.

The Random.Next method generates a random integer and by passing the maximum length of the array means the random number cannot be greater than the number of items in the array. 

using System;  
public class RandomStringInArraySample  
{  
public static void Main()  
{  
// A array of authors  
string[] authors = { "Mahesh Chand", "Jeff Prosise", "Dave McCarter", "Allen O'neill",  
"Monica Rathbun", "Henry He", "Raj Kumar", "Mark Prime",  
"Rose Tracey", "Mike Crown" };  
  
// Create a Random object  
Random rand = new Random();  
// Generate a random index less than the size of the array.  
int index = rand.Next(authors.Length);  
// Display the result.  
Console.WriteLine($"Randomly selected author is {authors[index]}");  
  
Console.ReadKey();  
}  
}  

 

Figure 1

 

Figure 2

Summary

In this article and code snippet, we discussed how to select a random string from an array of strings. 

Similar Articles
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.