---
title: "How can I generate a random integer in C#?"  
description: "How can I generate a random integer in C#?"  
author: "Steilla Mitchel"  
published: 2023-07-12  
updated: 2023-07-13  
canonical: https://www.mindstick.com/forum/159045/how-can-i-generate-a-random-integer-in-c-sharp  
category: "c#"  
tags: ["c#", "programs"]  
reading_time: 2 minutes  

---

# How can I generate a random integer in C#?

How can I generate a [random](https://www.mindstick.com/forum/33419/generating-random-numbers-in-objective-c) [integer in C#](https://www.mindstick.com/forum/557/converting-hex-to-integer-in-c-sharp)?

## Replies

### Reply by Aryan Kumar

Sure, here is how you can generate a random [integer](https://answers.mindstick.com/qa/113667/write-code-for-roman-to-integer) in C#:

C#

```plaintext
using System;

public class GenerateRandomInteger
{
    public static void Main(string[] args)
    {
        // Create a random number generator.
        Random random = new Random();

        // Generate a random integer between 0 and 100.
        int randomInteger = random.Next(101);

        // Print the random integer.
        Console.WriteLine("The random integer is {0}.", randomInteger);
    }
}
```

This code first creates a `Random` object. The `Random` object is used to generate random numbers.

The code then generates a random integer between 0 and 100. The `Next()` method of the `Random` object is used to generate a random number. The `Next()` method takes a maximum value as a parameter. The maximum value is exclusive, so the random number will be between 0 and the maximum value - 1.

Finally, the code prints the random integer to the console.

Here is an explanation of the code:

- The `using` statement is used to import the `System` namespace. The `System` namespace contains the `Random` class.
- The `Random` class is used to generate random numbers.
- The `Next()` method of the `Random` class is used to generate a random number.
- The `Console.WriteLine()` method is used to print a string to the console.


---

Original Source: https://www.mindstick.com/forum/159045/how-can-i-generate-a-random-integer-in-c-sharp

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
