...

/

Disadvantages of System.Random in C#

Disadvantages of System.Random in C#

In this lesson, we introduce the System.Random in C# and highlight some of the problems with it.

Introducing System.Random

The C# design team tries hard to make the language a pit of success, where the natural way to write programs is also the correct, elegant and performant way. And then System.Random comes along; it is almost always wrong, and it is seldom easy to make it right.

Let’s start with the obvious problem: the natural way to use it is also the wrong way.

The naive developer thinks “I need a new random dice roll”

void M()
{
  Random r = new Random();
  int x = r.Next(1, 6);
  ...

Let’s highlight some of the issues with this code.

Problem with System.Random

Firstly, every time M() is called, we create a new Random, but in most of the implementations of Random available for the last couple decades, by default, it seeds itself ...