Home > Backend Development > C#.Net Tutorial > Random Number Generator in C#

Random Number Generator in C#

WBOY
Release: 2024-09-03 15:34:50
Original
714 people have browsed it

A random number generator is a built-in library in C# that generates integers and floating-point numbers randomly. Each time the library’s relevant method is invoked, it returns a random number. A series of random numbers is a set of numbers that do not follow any pattern. The random number generator in C# tends to generate such a series whenever invoked.

Random Class in C#

  • So, how does C# generate a series of random numbers? The answer lies within the Random Class of the C# System namespace.
  • Random class is a pseudo-random number generator class. This means that this class is tasked to generate a series of numbers which do not follow any pattern. But, is a machine is truly capable of generating random numbers? How would the machine know which number to generate next? After all, the machine is designed to follow instructions and execute algorithms.
  • No, the machine cannot generate random numbers on its own. There is a defined mathematical algorithm, based on the current clock and state of the machine, which guides it to pick numbers from a set. All the numbers in the set have an equal probability of being picked up. Thus, they are not perfectly random. They do follow a pattern. It’s just that the pattern is sufficiently random to meet the practical human requirements.

Pseudo and Secure

The next question that comes to the mind is why do they call it pseudo-random number generator class? Let us understand this through real-life human behaviour. When a human being is asked to select a random colour, he picks up a certain colour. Let’s say he picked Yellow. What caused him to pick yellow? It could be his favourite colour or the colour of his surroundings, or he could have been thinking about something yellow at the time. This human behaviour which drives the decision to pick something randomly is called the Seed in the world of random-ness. The seed is the trigger or the beginning point of the random-ness.

Now, when the seed is predictable, the random numbers become less random. They are then called pseudo-random numbers. When unpredictable, they are called secure-random numbers.

C# Random Class uses the current timestamp as the seed, which is very much predictable. And hence, the term pseudo-random number generator class.

RNGCryptoServiceProvider Class

The RNGCryptoServiceProvider Class from the System.Security.Cryptography namespace is capable of generating secure random numbers, ones that can be used as passwords.

Random Number Generator Functions in C#

The first thing to generate a random number in C# is to initialize the Random class. This can be done by any of the two constructors of the class:

  • Random(): Initializes an object of the Random class using a time-based seed value. The seed value is the current timestamp of the machine. Although, in later versions, this was changed to be GUID based.
  • Random(Int32): Initializes an object of the Random class using the specified seed value. To get the next random number from the series, we call the Next() method of the Random class.
  • Next(): Returns a non-negative pseudo-random Int32 integer.
  • Next(Int32): Returns a non-negative pseudo-random Int32 integer less than the specified integer.
  • Next(Int32, Int32): Returns a non-negative pseudo-random Int32 integer within the specified range.

Random Number Generator Integers in C#

Let us see an example of how to generate random integers:

Example #1

The below example generates random Int32 numbers.

Code:

using System;
public class Program
{
public static void Main()
{
Random rnd = new Random();
for (int i = 0; i < 10; i++)
Console.WriteLine("Random number {0} : {1}", i + 1, GenerateRandomInt(rnd));
}
public static int GenerateRandomInt(Random rnd)
{
return rnd.Next();
}
}
Copy after login

Output:

Random Number Generator in C#

Example #2

The below example generates random Int32 numbers in the range 0 to 100.

Code:

using System;
public class Program
{
public static void Main()
{
Random rnd = new Random();
for (int i = 0; i < 10; i++)
Console.WriteLine("Random number {0} : {1}", i + 1, GenerateRandomInt(rnd));
}
public static int GenerateRandomInt(Random rnd)
{
return rnd.Next(100);
}
}
Copy after login

Output:

Random Number Generator in C#

Example #3

The below example generates random Int32 numbers in the range 50 to 100.

Code:

using System;
public class Program
{
public static void Main()
{
Random rnd = new Random();
for (int i = 0; i < 10; i++)
Console.WriteLine("Random number {0} : {1}", i + 1, GenerateRandomInt(rnd));
}
public static int GenerateRandomInt(Random rnd)
{
return rnd.Next(50, 100);
}
}
Copy after login

Output:

Random Number Generator in C#

Generating Floating-Point Numbers in C#

Let us see an example of how to generate random floating-point numbers:

Example #1

The below example generates random Int32 numbers.

Code:

using System;
public class Program
{
public static void Main()
{
Random rnd = new Random();
for (int i = 0; i < 10; i++)
Console.WriteLine("Random number {0} : {1}", i + 1, GenerateRandomInt(rnd));
}
public static double GenerateRandomInt(Random rnd)
{
return rnd.NextDouble();
}
}
Copy after login

Output:

Random Number Generator in C#

A Very Common Mistake

The most common mistake developers commit while generating random numbers is that for each random number, they create a new object of Random Class. As illustrated in the example below:

Example #1

Code:

using System;
public class Program
{
public static void Main()
{
for (int i = 0; i < 10; i++)
Console.WriteLine("Random number {0} : {1}", i + 1, GenerateRandomInt());
}
public static int GenerateRandomInt()
{
Random rnd = new Random();  //a very common mistake
return rnd.Next();
}
}
Copy after login

Output:

Random Number Generator in C#

How Random Numbers are all the same and Why did this happen?

As explained in the working of Random Class, the numbers generated are based on the seed value and the current state of the machine. Any instance of Random class starts with the seed value, saves the current state and uses it to generate the next random number. In the code above, the mistake was to create a new instance of the Random class in every iteration of the loop. So, before the time in the internal clock changes, the code is fully executed, and each instance of Random class is instantiated with the same seed value. This results in the same set of numbers generated every time.

Conclusion

In this article, we learnt about the random number generator in C# and how it internally works to generate random numbers. We also briefly learnt the concept of pseudo-random and secure-random numbers. This information is sufficient for developers to use the Random class in their applications. Deep dive, if interested to explore more on random numbers for passwords and one-time passwords.

The above is the detailed content of Random Number Generator in C#. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template