How to generate a random integer in C#?

In this tutorial, you will learn how to generate a random integer in C#.

“C# offers the Random class for creating random numbers using a seed value. You can generate random numbers by using the following methods of the Random class.”

Here are some methods and descriptions you can do with the Random class in C#.

  • Next(): Get a positive random integer within the default range of -2,147,483,648 to 2,147,483,647.
  • Next(int): Grab a positive random integer smaller than your chosen maximum value.
  • Next(int, int): Score a positive random integer within a specific range (including the minimum and excluding the maximum).
  • NextDouble(): Snag a random floating-point number between 0.0 (inclusive) and 1.0 (exclusive).
  • NextByte(): Fill up an array with some rad random bytes.”

“Check out this cool example that shows you how to create random integers in C#!

// Single Random Integer
Random rnd = new Random();
int num = rnd.Next();

// Multiple Random Integers
Random rnd = new Random();
for (int j = 0; j < 4; j++)
{
    Console.WriteLine(rnd.Next());
}

Output:

1472153342
-982736501
2089758563
-1946832104

Just keep calling Next() to get as many random numbers as you want. Each call to rnd.Next() produces a random integer, so the values will vary each time you execute the code.

Another example

“Let’s dive into the world of randomness with the Random class in C#! 🎲 (Well, technically pseudo-random, but let’s not get too technical!)

Check out this example:

// Creating Random Numbers
Random rnd = new Random();
int month  = rnd.Next(1, 13);  // Generates a number between 1 and 12
int dice   = rnd.Next(1, 7);   // Rolls a number between 1 and 6
int card   = rnd.Next(52);     // Picks a number between 0 and 51

// Reusing the Random Instance
// If you need more random numbers, keep using the same Random instance
// Creating new instances too close may give you the same series of numbers

Now you’re all set to sprinkle some randomness into your code!

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top