We can create random strings in C# using the Random class. The Random class of .NET provides functionality to generate random numbers, strings, and other data types.
The following code example generates a random string of a given length.
using System.Text;
namespace Namespace8
{
class RandomNumberSample
{
static void Main(string[] args)
{
var generator = new RandomGenerator();
var randomString = generator.RandomString(10);
Console.WriteLine($"Random string of 10 chars is {randomString}");
Console.ReadKey();
}
}
public class RandomGenerator
{
// Instantiate random number generator.
// It is better to keep a single Random instance
// and keep using Next on the same instance.
private readonly Random _random = new Random();
// Generates a random string with a given size.
public string RandomString(int size, bool lowerCase = false)
{
var builder = new StringBuilder(size);
// Unicode/ASCII Letters are divided into two blocks
// (Letters 65–90 / 97–122):
// The first group containing the uppercase letters and
// the second group containing the lowercase.
// char is a single Unicode character
char offset = lowerCase ? 'a' : 'A';
const int lettersOffset = 26; // A...Z or a..z: length = 26
for (var i = 0; i < size; i++)
{
var @char = (char)_random.Next(offset, offset + lettersOffset);
builder.Append(@char);
}
return lowerCase ? builder.ToString().ToLower() : builder.ToString();
}
}
}
As you can see from the above example, the Random class is the magician. It provides Random.Next(), Random.NextBytes(), and Random.NextDouble() methods. The Random.Next() method returns a random number, Random.NextBytes() returns an array of bytes filled with random numbers and Random.NextDouble() returns a random number between 0.0 and 1.0.
Hope you find this code snippet useful.

ethan kleinPosted Feb 7, 2023, 8:42 AM
You can generate a random string in C# by using the System.Random class and the Next method to generate random characters. You can use a loop to generate the desired length of the string and concatenate the characters to form the final string. Here's an example that generates a random string of length 10 with uppercase letters: csharp Copy code using System; namespace RandomStringGenerator { class Program { static void Main(string[] args) { Random random = new Random(); const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; int length = 10; string randomString = new string(Enumerable.Repeat(chars, length) .Select(s => s[random.Next(s.Length)]).ToArray()); Console.WriteLine(randomString); } } } You can modify the chars variable to include other characters or character sets as needed.