C# Code Snippets

Submit a Comment

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];
    
    rng.GetBytes(buffer);
    int result = BitConverter.ToInt32(buffer, 0);

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

Back to C# Code Snippet List

Other CSharp Articles

Visual C# Kicks Newsletter
Visual C# Kicks RSS Feed
License Agreement | Privacy Policy
Link to Us | Subscribe to Newsletter | Contact Us