Table of Contents
Random Class in C#
Pseudo and Secure
RNGCryptoServiceProvider Class
Random Number Generator Functions in C#
Random Number Generator Integers in C#
Example #1
Generating Floating-Point Numbers in C#
A Very Common Mistake
How Random Numbers are all the same and Why did this happen?
Conclusion
Home Backend Development C#.Net Tutorial Random Number Generator in C#

Random Number Generator in C#

Sep 03, 2024 pm 03:34 PM
c# c# tutorial

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Active Directory with C# Active Directory with C# Sep 03, 2024 pm 03:33 PM

Guide to Active Directory with C#. Here we discuss the introduction and how Active Directory works in C# along with the syntax and example.

C# Serialization C# Serialization Sep 03, 2024 pm 03:30 PM

Guide to C# Serialization. Here we discuss the introduction, steps of C# serialization object, working, and example respectively.

Random Number Generator in C# Random Number Generator in C# Sep 03, 2024 pm 03:34 PM

Guide to Random Number Generator in C#. Here we discuss how Random Number Generator work, concept of pseudo-random and secure numbers.

C# Data Grid View C# Data Grid View Sep 03, 2024 pm 03:32 PM

Guide to C# Data Grid View. Here we discuss the examples of how a data grid view can be loaded and exported from the SQL database or an excel file.

Patterns in C# Patterns in C# Sep 03, 2024 pm 03:33 PM

Guide to Patterns in C#. Here we discuss the introduction and top 3 types of Patterns in C# along with its examples and code implementation.

Factorial in C# Factorial in C# Sep 03, 2024 pm 03:34 PM

Guide to Factorial in C#. Here we discuss the introduction to factorial in c# along with different examples and code implementation.

Prime Numbers in C# Prime Numbers in C# Sep 03, 2024 pm 03:35 PM

Guide to Prime Numbers in C#. Here we discuss the introduction and examples of prime numbers in c# along with code implementation.

The difference between multithreading and asynchronous c# The difference between multithreading and asynchronous c# Apr 03, 2025 pm 02:57 PM

The difference between multithreading and asynchronous is that multithreading executes multiple threads at the same time, while asynchronously performs operations without blocking the current thread. Multithreading is used for compute-intensive tasks, while asynchronously is used for user interaction. The advantage of multi-threading is to improve computing performance, while the advantage of asynchronous is to not block UI threads. Choosing multithreading or asynchronous depends on the nature of the task: Computation-intensive tasks use multithreading, tasks that interact with external resources and need to keep UI responsiveness use asynchronous.

See all articles