EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

Random Number Generator in C#

By Priya PedamkarPriya Pedamkar

Home » Software Development » Software Development Tutorials » C# Tutorial » Random Number Generator in C#

Random Number Generator in C#

What is Random Number Generator in C#?

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.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

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();
}
}

Popular Course in this category
C# Training Program (6 Courses, 17 Projects)6 Online Courses | 17 Hands-on Project | 89+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.6 (8,847 ratings)
Course Price

View Course

Related Courses
ASP.NET Training (8 Courses, 19 Projects).NET Training Program (4 Courses, 19 Projects)

Output:

random c#1

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);
}
}

Output:

random c#2

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);
}
}

Output:

random c#3

Generating Floating-Point Numbers

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();
}
}

Output:

random c# 4

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();
}
}

Output:

random c# 5

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.

Recommended Articles

This is a guide to Random Number Generator in C#. Here we discuss how Random Number Generator work, the concept of pseudo-random and secure-random numbers and the use of Random Number. You can also go through our other related articles to learn more –

  1. Reverse Number in Python
  2. Random Number Generator in Matlab
  3. Random Number Generator in JavaScript
  4. Random Number Generator in PHP

C# Training Program (6 Courses, 17 Projects)

6 Online Courses

17 Hands-on Project

89+ Hours

Verifiable Certificate of Completion

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
C sharp Tutorial
  • Programs
    • Patterns in C#
    • Swapping in C#
    • Palindrome in C#
    • Factorial in C#
    • Fibonacci Series in C#
    • Random Number Generator in C#
    • Prime Numbers in C#
    • Armstrong Number in C#
    • Reverse String in C#
  • Basic
    • Uses Of C#
    • C# Versions
    • C# Data Types
    • Variables in C#
    • Namespaces in C#
    • C# Compilers
    • C# Keywords
    • Iterators in C#
    • Objects in C#
    • C# Object Dispose
    • C# object to XML
    • C# check object type
    • C# Object Serialization
    • Pointers in C#
    • C# Literals
    • C# Commands
    • C# Custom Attribute
    • Type Casting in C#
    • String vs String C#
    • C# Struct vs Class
  • Operators
    • Logical Operators in C#
    • Conditional Operators in C#
    • Bitwise Operators in C#
    • C# OR Operator
    • C# Ternary Operators
    • Operator Precedence in C#
  • Control Statement
    • C# if Statement
    • Else If in C#
    • Continue in C#
    • Break in C#
    • Switch Statement in C#
    • Goto Statement in C#
  • Loops
    • C# For Loop
    • C# While Loop
    • C# do-while loop
    • C# foreach Loop
  • Arrays
    • Arrays in C#
    • 2D Arrays in C#
    • C# Jagged Arrays
    • String Array in C#
    • C# Multidimensional Arrays
  • Constructor and Destructor
    • Constructor in C#
    • Copy Constructor in C#
    • Static Constructor in C#
    • Destructor in C#
  • overloading and overrideing
    • Overloading and Overriding in C#
    • Overloading in C#
    • Overriding in C#
    • Method Overloading in C#
    • Method Overriding in C#
    • Operator Overloading in C#
  • Functions
    • C# Functions
    • C# String Functions
    • Math Functions in C#
    • Recursive Function in C#
    • C# Anonymous Functions
    • C# Local Functions
    • Enum in C#
    • Trim() in C#
    • clone() in C#
    • C# random
    • C# String Format()
    • C# String Interpolation
    • C# StartsWith()
    • C# String IndexOf()
    • DateTime in C#
    • C# Nullable
    • C# nameof
    • C# checked
    • C# String PadLeft
    • Convert String to Double in C#
    • Convert int to String C#
    • String to Date C#
    • C# intern()
    • C# Stopwatch
    • C# DirectoryInfo
    • C# Compare()
    • C# Base
    • C# SOAP
    • Lock in C#
  • Advanced
    • Inheritance in C#
    • Exception Handling in C#
    • Types of Exception in C#
    • C# FileNotFoundException
    • C# NullReferenceException
    • C# OutOfMemoryException
    • C# StackOverflowException
    • Custom Exception in C#
    • What is Multithreading in C#
    • C# finally
    • C# System.IO
    • What is StringBuilder in C#
    • DataReader C#
    • BinaryWriter in C#
    • C# BinaryReader
    • TextWriter in C#
    • TextReader in C#
    • C# StringReader
    • C# StringWriter
    • C# StreamReader
    • C# StreamWriter
    • C# FileInfo
    • What is Design Pattern in C#?
    • Multithreading in C#
    • Sorting in C#
    • Bubble Sort in C#
    • C# SortedList
    • C# SortedSet
    • C# SortedDictionary
    • Abstract Class in C#
    • Access Modifiers in C#
    • C# Generics
    • Deserialization in C#
    • C# Thread
    • C# Thread Join
    • C# Thread Sleep
    • C# Thread Synchronization
    • C# Class
    • Sealed in C#
    • Sealed Class in C#
    • Polymorphism in C#
    • C# Call By Reference
    • Virtual Keyword in C# 
    • Yield Keyword in C#
    • Regular Expression in C#
    • C# Lambda Expression
    • C# Predicate
    • Convert Object to JSON C#
    • Checkbox in C#
    • C# MessageBox
    • Collections in C#
    • List in C#
    • C# LinkedList
    • Listbox in C#
    • Protected in C#
    • C# EventHandler
    • Private in C#
    • this Keyword in C#
    • Static Keyword in C#
    • C# Out Parameter
    • Assert in C#
    • C# Delegates
    • C# Interface
    • Generics in C#
    • Timer in C#
    • C# Serialization
    • Metadata in C#
    • C# Stack
    • C# Using Static
    • Queue in C#
    • C# File.Exists
    • C# Tuples
    • C# Create JSON Object
    • Partial in C#
    • C# readonly
    • C# Action Delegate
    • C# Await Async
    • C# Dictionary
    • IEnumerable C#
    • C# Data Grid View
    • C# Dynamic
    • Web Services in C#
    • C# Pattern Matching
    • C# Extension Methods
    • C# XmlSerializer
  • Interview questions
    • C# Interview Questions and Answers
    • C# OOP Interview Questions
    • C# Design Pattern Interview Questions

Related Courses

C# Certification Training

ASP.NET Course

.NET Course

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - C# Training Program (6 Courses, 17 Projects) Learn More