To generate a random integer in C#, you can use the Random class from the System namespace.
Here’s an example:
Example: Generate a Random Integer
sharp Copy code
using System;
class Program
{
static void Main()
{
// Create a Random object
Random random = new Random();
// Generate a random integer
int randomNumber = random.Next(); // Generates a non-negative random integer
Console.WriteLine(“Random Number: ” + randomNumber);
// Generate a random integer within a range (e.g., 1 to 100)
int randomInRange = random.Next(1, 101); // Upper bound is exclusive
Console.WriteLine(“Random Number (1-100): ” + randomInRange);
}
}
Key Points:
Random.Next():
Without parameters: Generates a random integer from 0 to Int32.MaxValue (inclusive).
With parameters: Next(int minValue, int maxValue) generates a random integer between minValue (inclusive) and maxValue (exclusive).
Reusability:
Avoid creating multiple Random objects in a short time (e.g., in a loop) to ensure randomness, as they may use the same seed.