generate a random number between 1 and 100 in csharp

To generate a random number between 1 and 100 in C#, you can use the Random class provided by the .NET framework. Here's a code snippet that does just that:

main.cs
Random random = new Random();
int randomNumber = random.Next(1, 101); // Generates a random number between 1 and 100 (inclusive)
Console.WriteLine(randomNumber); // Prints the generated random number
200 chars
4 lines

Explanation:

  • We first create a new Random object that we'll use to generate the random number.
  • We then call the Next method of the Random object, passing in the lower and upper bounds of the random number we want to generate (1 and 101, respectively). Note that the upper bound (101) is exclusive, so the generated number can be any integer in the range [1, 100].
  • Finally, we print out the generated random number using Console.WriteLine.

gistlibby LogSnag