Brettb.Com
  HOME | ABOUT ME | BIOTECHNOLOGY | ARTICLES | GALLERY | CONTACT
Search: Go
TECHNICAL ARTICLES
 ASP
 ASP.NET
 JavaScript
 Transact SQL
 Other Articles
 Software Reviews

PHOTO GALLERIES
 Canon EOS 300D Samples
 Akihabara Maids!
 More Galleries...

TRAVEL LOG
 2009: China
 2008: Tokyo
 2007: Tokyo
 2006: Hong Kong
 2005: New York City

MORE STUFF
 Search Engine Optimisation
 Build an ASP Search Engine
 My Tropical Fishtank
 Autoglass
 SQL Month Name
 SQL Get Date Today
 SQL Year Month
 Other New Stuff...

POPULAR STUFF
 Regular Expressions
 Index Server & ASP
 JavaScript Ad Rotator

Home > ASP.NET Articles

Generating Random Numbers in the .NET Framework

Random numbers may be generated in the .NET Framework by making use of the Random class. This class may be instantiated using the following code:

//Create a new Random class in C#
Random RandomClass = new Random();

'Create a new Random class in VB.NET
Dim RandomClass As New Random()

Random Integers

Once the class has been instantiated, a random integer can be obtained by calling the Next method of the Random class:

//C#
int RandomNumber = RandomClass.Next();

'VB.NET
Dim RandomNumber As Integer
RandomNumber = RandomClass.Next()

The value of RandomNumber will, therefore, be assigned a random whole number between 1 and 2,147,483,647.

In most coding situations, it is more desirable to create a random number within a certain size range. In this case, the Next method should be called with two arguments: the minimum value and the maximum value. For example, the following assigns RandomNumber to a value that is greater or equal to 4 and less than 14:

//C#
int RandomNumber = RandomClass.Next(4, 14);

'VB.NET
Dim RandomNumber As Integer
RandomNumber = RandomClass.Next(4, 14)

Note that an ArgumentOutOfRangeException will be raised if the minimum value is larger than the maximum value.

It is also possible to specify just the maximum value using a different constructor. The following will return a return a random integer that is greater or equal to 0 and less than 14:

//C#
int RandomNumber = RandomClass.Next(14);

'VB.NET
Dim RandomNumber As Integer
RandomNumber = RandomClass.Next(14)

Again, an ArgumentOutOfRangeException will be raised if the maximum value is smaller than 0.

Random Floating Point Numbers

As well as returning random integers, the Random class can also return floating point numbers. The NextDouble method returns a random number as a Double. The random number's value is always greater or equal to 0.0, and less than 1.0:

//Create a random double using C#
double RandomNumber = RandomClass.NextDouble();

'Create a random double using VB.NET
Dim RandomNumber As Double
RandomNumber = RandomClass.NextDouble()

  Site Map | Privacy Policy

All content is 1995 - 2012