Unique Random Number Generator Class (C# .NET)

March 26, 2008 at 12:00 pm Leave a comment

This is a class for generating an absolute unique random number. The class works by removing selected numbers from a list once they’ve been selected, so it’s impossible for them to be selected again, thus making it possible to simulate real life random number selection in lottery type scenarios.

Pass the maximum and minimum numbers that you would like returned from the class to the constructor when creating the object.

Download Code File: GenerateUniqueRandomNumbers.cs

using System;
using System.Collections.Generic;
using System.Text;

/// <summary>
/// Class for generating unique random numbers within a given range. Removes numbers from list
/// once chosen from an instance of an object so that it is impossible for them to be selected again.
/// </summary>
public class GenerateUniqueRandomNumber
Random m_random = new Random();

int m_newRandomNumber = 0;

List<int> RemainingNumbers;

// Constructor
public GenerateUniqueRandomNumber( int requiredRangeLow, int requiredRangeHi )
// Get the range
int range = (requiredRangeHi – requiredRangeLow);

// Initialise array that will hold the numbers within the range
int[] rangeNumbersArr = new int[range + 1];

// Assign array element values within range
for (int count = 0; count < rangeNumbersArr.Length; count++)
rangeNumbersArr[count] = requiredRangeLow + count;

// Initialize the List and populate with values from rangeNumbersArr
RemainingNumbers = new List<int>();

/// <summary>
/// This method returns a random integer within the given range. Each call produces a new random number
/// </summary>
/// <returns></returns>
public int NewRandomNumber()
if (RemainingNumbers.Count != 0)
// Select random number from list
int index = m_random.Next(0, RemainingNumbers.Count);
m_newRandomNumber = RemainingNumbers[index];

// Remove selected number from Remaining Numbers List

return m_newRandomNumber;
throw new System.InvalidOperationException(“All numbers in the range have now been used. Cannot continue selecting random numbers from a list with no members.”);


Entry filed under: ASP.NET, C#. Tags: , , , , , , .

A Couple of Quick Tips on Setting Up IIS 5 (XP) Lotto Number Generator Form Class (C# .NET)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

Trackback this post  |  Subscribe to the comments via RSS Feed


March 2008
    May »

Most Recent Posts

%d bloggers like this: