How to Generate a Random Number and Random String in C#?

C# Random class provides functionality to generate random numbers in C#. The Random class can also generate other data types, including strings. In this code example, learn how to create a random number in C#. 

Random class constructors have two overloaded forms. It takes either no value, or it takes a seed value. The Random class 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.

The Random.Next() method has three overloaded forms and allows you to set the minimum and maximum range of the random number.

The following code returns a random number. 

int num = random.Next(); 

The following code returns a random number less than 1000.

int num = random.Next(1000);

The following code returns a random number between the min and the max range.

// Instantiate random number generator.  
private readonly Random _random = new Random();  
  
// Generates a random number within a range.      
public int RandomNumber(int min, int max)  
{  
  return _random.Next(min, max);  
}

You can even combine the two methods - RandomNumber and RandomString to generate a combination of random strings and numbers.  

// 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();  
}  

The following code generates a password of length 10 with the first 4 letters lowercase, the next 4 letters numbers, and the last 2 letters as uppercase. 

// Generates a random password.  
// 4-LowerCase + 4-Digits + 2-UpperCase  
public string RandomPassword()  
{  
  var passwordBuilder = new StringBuilder();  
  
  // 4-Letters lower case   
  passwordBuilder.Append(RandomString(4, true));  
  
  // 4-Digits between 1000 and 9999  
  passwordBuilder.Append(RandomNumber(1000, 9999));  
  
  // 2-Letters upper case  
  passwordBuilder.Append(RandomString(2));  
  return passwordBuilder.ToString();  
}  

Here is the complete code written in .NET Core 5.0. using System;  
using System.T

namespace ConsoleApp7  
{  
  class RandomNumberSample  
  {  
    static void Main(string[] args)  
    {  
      var generator = new RandomGenerator();  
      var randomNumber = generator.RandomNumber(5, 100);  
      Console.WriteLine($"Random number between 5 and 100 is {randomNumber}");  
  
      var randomString = generator.RandomString(10);  
      Console.WriteLine($"Random string of 10 chars is {randomString}");  
  
      var randomPassword = generator.RandomPassword();  
      Console.WriteLine($"Random string of 6 chars is {randomPassword}");  
  
      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 number within a range.      
    public int RandomNumber(int min, int max)  
    {  
      return _random.Next(min, max);  
    }  
  
    // 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();  
    }  
  
    // Generates a random password.  
    // 4-LowerCase + 4-Digits + 2-UpperCase  
    public string RandomPassword()  
    {  
      var passwordBuilder = new StringBuilder();  
  
      // 4-Letters lower case   
      passwordBuilder.Append(RandomString(4, true));  
  
      // 4-Digits between 1000 and 9999  
      passwordBuilder.Append(RandomNumber(1000, 9999));  
  
      // 2-Letters upper case  
      passwordBuilder.Append(RandomString(2));  
      return passwordBuilder.ToString();  
    }  
  }  
}  

The output from the above code is shown in figure 1.


Figure 1. Console Output

Summary

This article and code example taught you how to generate random numbers and random strings in C#.


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.