You might be wondering why would we need the Random Class in C#? One obvious example that comes to mind would be computer games. Whether attempting to simulate the rolling of dice or mimicking a random event, getting the same result every time would clearly not be fun.

Perhaps a more serious example would be in the world of cryptography, which requires random number generation for encryption algorithms. Even simple applications, such as randomly selecting a person from a database to be a juror, require the use of generating a random result.

As such, we are going to explore throughout this article how to use the Random Class in C# to generate these random results.

To download the source code for this article, you can visit our GitHub repository.

Let’s start.

What Are Computer Generated Numbers?

When creating a random number, we have to remember that nothing involving a computer is truly random; there has to be some type of input in order to get a result. With that in mind, there are two types of random number generators:  pseudorandom numbers and secure random numbers. 

Pseudorandom numbers are generated by an algorithm. Consequently, if we were to provide the same input every time, we would get the same number of results. 

Secure random numbers are generated by gathering some sort of outside data that is constantly changing. For example, a secure random number would be generated by using the current CPU fan speed of the PC’s motherboard in correlation with an algorithm.

Neither of these methods is incorrect. We must just be aware of our use case and what is an appropriate solution for the current situation. For instance, we would not want to use a pseudorandom number algorithm to generate encryption keys that hackers could guess and exploit.

For the purpose of this article, we will mainly be using C#’s built-in pseudorandom Random class to generate random data.

How to Use Random Class in C#?

C# makes creating a Random number very straightforward with a simple initializing of the Random class followed by the .Next() method:

var random = new Random();
var rNum = random.Next();

For a more in-depth look at generating Random integers in C# see this article.

Accordingly, we can use similar syntax to generate Random doubles:

var random = new Random();
var rDouble = random.NextDouble();

For even more specifics regarding generating Random double numbers in C# take a look at this article.

How to Generate Thread-Safe Random Numbers?

The previous examples work well when we need to generate random numbers; however, what should we do when we need a parallel solution? If we attempt to use the same Random class instance across multiple threads, at the very least, we would encounter the same number always returned, and at the worst, crash our program with race conditions.

Thankfully, version 6 of .NET provides a Random.Shared static property that allows for a thread-safe implementation avoiding the need for us to implement our own locking mechanism:

Wanna join Code Maze Team, help us produce more awesome .NET/C# content and get paid? >> JOIN US! <<

var random = Random.Shared.Next();

Because the Random.Shared.Next() is a static method, we do not need to initialize the Random class before accessing it.

How to Generate Random Strings?

Generating a random string involves using the Random class’s Next() method within a loop to choose the characters within the string.

So, let’s see that with an example:

const string alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
var random = new Random();
var pseudoRandomChars = new char[stringLength];

We begin by declaring a string that contains the list of characters we wish to choose from (we can also include numbers and symbols). Next, we initialize a new instance of the Random class. After which, we create a new character array with the desired length of the random string.

Next, we follow with a for loop that populates every character in the array with a random character:

for (int i = 0; i < stringLength; ++i)
{
    int charIndex = random.Next(alphabet.Length);
    pseudoRandomChars[i] = alphabet[charIndex];
}

var pseudoRandomString = new string(pseudoRandomChars);

Once the loop is finished, we create a new string with the pseudo-randomly generated character array.

Using Our Own Algorithm to Generate Random Data

There are times when we wish to generate random data in a particular way that is not confined to the current Random class algorithm. We can change this with inheritance by overriding Random class’s Sample method, which contains the algorithm to generate the random data:

Wanna join Code Maze Team, help us produce more awesome .NET/C# content and get paid? >> JOIN US! <<
public class RandomCustom : Random
{
    protected override double Sample()
    {
        return ModifySample(base.Sample());
    }

    private double ModifySample(double sample)
    {
        double newSample = Math.Log(sample);
        return newSample;
    }

    public override int Next()
    {
        return (int)(Sample() * int.MaxValue);
    }
}

Notice here, that we are just taking whatever the base sample value is and modifying it with a mathematical operation.

Then to use this overridden method, we are going to initialize the RandomCustom class and call Next():

var rc = new RandomCustom();
var customAlgorithmPsuedoRandomNumber = rc.Next();

Is Random Class Really Random?

Random is a pseudo-random number generator. As a result, the numbers generated are not truly random, and someone can guess these numbers with enough time and effort. Accordingly, if you wish to generate cryptographically secure random data, you will need to use C#’s RandomNumberGenerator class.

RandomNumberGenerator contains methods, with some slight parameter variation, that we can call in a very similar way as with the Random class.

If you wish to learn more about how to specifically generate cryptographically secure integers or doubles, please follow the article links mentioned above.

Conclusion

In conclusion, the two main ways to generate random numbers in C# are using the Random and RandomNumberGenerator classes. These pseudo-random and secure random generators provide the flexibility to generate random numbers in C# in a way that best fits your current need.

Furthermore, these classes do not restrict you to just numeric values, you can use these to generate random strings as well. The C# language provides excellent tools for us to quickly and efficiently generate random numbers in C#.

Wanna join Code Maze Team, help us produce more awesome .NET/C# content and get paid? >> JOIN US! <<