# C#: How to Generate a Random or Secure Random Integer

> Generate pseudorandom integers in C# with System.Random, or cryptographically secure random numbers using RandomNumberGenerator for security-sensitive code

**URL:** https://sentry.io/answers/generate-a-random-integer-in-csharp/

---

## The Problem

How do I generate a random integer in C#?

## The Solution

We can generate pseudorandom numbers using C#'s [`System.Random`](https://learn.microsoft.com/en-us/dotnet/api/system.random?view=net-8.0) class. For example:

```csharp
Random rng = new Random();

int rand1 = rng.Next(100); // number between 0 and 99
```

We can also specify a lower bound for generated numbers:

```csharp
int rand2 = rng.Next(10, 20); // number between 10 and 19
```

Note that the randomness generated by calling `rng.Next` is only pseudorandom, not truly random. This is sufficient for applications where true randomness is not critical, such as games or visualizations, but should not be used for anything related to security.

To generate truly random numbers, we should use the `RandomNumberGenerator` class from `System.Security.Cryptography`. For example:

```csharp
var randomBytes = new byte[4];

using (var rng = RandomNumberGenerator.Create())
{
    rng.GetBytes(randomBytes);
    uint trueRandom = BitConverter.ToUInt32(randomBytes, 0);
}
```

---

*Source: [sentry.io/answers/generate-a-random-integer-in-csharp/](https://sentry.io/answers/generate-a-random-integer-in-csharp/)*
