I was working on a backend api part that required unique identification codes for sending otp to user when want to registered in our system and these codes needed to be random but also easy to read but generating these codes randomly while maintaining the desired format turned out to be a bit more easy than I initially thought.

So, if you've ever encountered this situation you can have look on below function,In this blog post, we'll shows you several ways to generate random 6-digit numbers in C#. We'll explore different approaches, from using the built-in Random class to LINQ and even exploring a DateTime.Now.Ticks. 

Generating Random 6-Digit Number in C#

When it comes to generating a random 6-digit number in C#, there are multiple approaches we can take. Let's explore five of the best ways to achieve this:

1: Using Random Class

We can utilize the `Random` class to generate random numbers, In approach we instantiate a Random object, which allows us to generate random numbers. By calling Next(100000, 999999), we specify that we want a random integer between 100,000 and 999,999.


using System;

Random random = new Random();
int randomNumber = random.Next(100000, 999999);
    

2: Using Guid

We can use the `Guid` class to generate a unique identifier and extract a portion of it,Here, we generate a new GUID using Guid.NewGuid() and convert it to a string and then, we extract the first 6 characters from the GUID string and parse it into an integer.


string randomString = Guid.NewGuid().ToString().Substring(0, 6);
int randomNumber = int.Parse(randomString);
    

3: Using RNGCryptoServiceProvider

With RNGCryptoServiceProvider, we can generate cryptographically strong random bytes. Then, we convert these bytes into an integer within the range of 100,000 to 999,999 so we can use `RNGCryptoServiceProvider` for generating cryptographically strong random numbers:


using System.Security.Cryptography;

byte[] randomNumberBytes = new byte[4];
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
rng.GetBytes(randomNumberBytes);
int randomNumber = BitConverter.ToInt32(randomNumberBytes, 0) % 900000 + 100000;
    

4: Using DateTime.Ticks

We can get the current time in ticks using DateTime.Now.Ticks, then use it as a seed for initializing a Random object,  to ensures a different seed for each call, providing relatively random numbers so we can also use `DateTime.Ticks` for a simple approach:


long ticks = DateTime.Now.Ticks;
Random random = new Random((int)(ticks & 0xFFFFFFFFL) | (int)(ticks >> 32));
int randomNumber = random.Next(100000, 999999);
    

5: Using SecureRandom (from System.Security.Cryptography)

We can implement a secure random number generator using `SecureRandom`,With SecureRandom, we generate a secure random number within the specified range directly.


using System.Security.Cryptography;

SecureRandom secureRandom = new SecureRandom();
int randomNumber = secureRandom.Next(100000, 999999);
    

6. Using LINQ with Enumerable.Range and Skip: 

This approach uses LINQ to create a sequence of digits, skip the first 5, and then join them into a string.We create a sequence of digits using Enumerable.Range, shuffle them using OrderBy(Guid.NewGuid()), skip the first 5 digits, and then take the next 6 to form our 6-digit number.

C#
public static string GetRandom6DigitNumberLinq()
{
    return string.Join("", Enumerable.Range(0, 10).OrderBy(x => Guid.NewGuid()).Skip(5).Take(6));
}
 

7. Using a loop and Random class: 

We can iterates 6 times, generating a random digit each time and concatenating them into a string.

C#
public static string GetRandom6DigitNumberLoop()
{
    Random random = new Random();
    string randomNumber = "";
    for (int i = 0; i < 6; i++)
    {
        randomNumber += random.Next(0, 10).ToString();
    }
    return randomNumber;
}
 

8. Using a recursive function: 

With recursion, we build the random number digit by digit until it reaches a length of 6, this approach solution based on recursion to build the random number digit by digit.

C#
public static string GetRandom6DigitNumberRecursive(string number = "")
{
    if (number.Length == 6)
    {
        return number;
    }
    return GetRandom6DigitNumberRecursive(number + new Random().Next(0, 10).ToString());
}
 


If choose in terms of performance, the best approach among the these option to be using the Random class first method.

Using Random Class this is a simple and straightforward solution and directly generates a random integer within the specified range, ensuring that the result is identically distributed.

One point to be note the Random class is generally suitable for non-cryptographic random number generation, it may not be cryptographically secure but for generating random 6-digit numbers where cryptographic security isn't a concern, this is not an issue.

If you only considering performance, the Random class provides a good balance between simplicity and efficiency for generating random 6-digit numbers. 

Random class efficient for generating non-cryptographically secure random numbers within the specified range without introducing unnecessary overhead. if in your application cryptographic security is a requirement, using RNGCryptoServiceProvider would be more suitable.

Generating Random 6-Digit Number in C# - Extension Methods

You can also create extensions so that you can easily use all these functions, so let's create extension methods for each of the provided solutions:

1. Using Random Class:

using System;

public static class RandomExtensions
{
    public static int Next6DigitNumber(this Random random)
    {
        return random.Next(100000, 999999);
    }
}
    

2. Using Guid:

using System;

public static class GuidExtensions
{
    public static int Random6DigitNumber(this Guid guid)
    {
        string randomString = guid.ToString().Substring(0, 6);
        return int.Parse(randomString);
    }
}
    

3. Using RNGCryptoServiceProvider:

using System;
using System.Security.Cryptography;

public static class RNGCryptoServiceProviderExtensions
{
    public static int Next6DigitNumber(this RNGCryptoServiceProvider rng)
    {
        byte[] randomNumberBytes = new byte[4];
        rng.GetBytes(randomNumberBytes);
        int randomNumber = BitConverter.ToInt32(randomNumberBytes, 0) % 900000 + 100000;
        return randomNumber;
    }
}