C# Code Snippets

RNGCryptoServiceProvider Random Integer

Using a combination of the Random and RNGCryptoServiceProvider .NET classes, we can generate uniformly distributed random integers within a given range.

Platform: .NET Framework 2.0

using System;
using System.Security.Cryptography;

private static int NextInt(int min, int max)
    RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
    byte[] buffer = new byte[4];
    int result = BitConverter.ToInt32(buffer, 0);

    return new Random(result).Next(min, max);

Back to C# Code Snippet List

Other C# Articles
Unable to connect to database! Please try again later.