How to use System.Random

Heres your chance to share your own tutorials with the community. Just post them on here. If your lucky they may even be posted on the main site.
3 posts Page 1 of 1
Contributors
User avatar
MrAksel
C# Coder
C# Coder
Posts: 1758
Joined: Fri Mar 26, 2010 12:27 pm

How to use System.Random
MrAksel
System.Random is a class that will generate random numbers. It can be used for many different things.
First up, declare a new random, named 'R' or whatever you want it to be.
To declare it, you can use two ways
Code: Select all
Dim R As New System.Random
or
Code: Select all
Dim R As New System.Random(Int32) 'Change Int32 to a number
The first way is just a shortcut for the second way, because it will call the second way with 'Enviroment.TickCount' as the Int32.
To get a random number, use the Next() method:
Code: Select all
Dim RandomNumber As Integer = R.Next() 'No parameters
Dim RandomNumber2 As Integer = R.Next(50) 'The parameter says the MaxValue
Dim RandomNumber3 As Integer = R.Next(10, 50) 'Parameter 1 = MinValue, Parameter 2 = MaxValue
All of these will create a Integer, but there is also a way for getting a Double:
Code: Select all
Dim RandomDouble As Double = R.NextDouble()
That will create a random number between 0.0 and 1.0

The NextBytes method will fill a buffer of bytes with random numbers:
Code: Select all
        Dim r As New Random
        Dim Bytes(9) As Byte '9 is the number of bytes in the array, but its not 9 its 10
        r.NextBytes(Bytes)
Thats the basics, and pretty much everything about the System.Random Class
LMAOSHMSFOAIDMT
Laughing my a** of so hard my sombrero fell off and I dropped my taco lmao;


Over 30 projects with source code!
Please give reputation to helpful members!

Image
Image
User avatar
Usman55
VIP - Site Partner
VIP - Site Partner
Posts: 2821
Joined: Thu Dec 24, 2009 7:52 pm

Re: How to use System.Random
Usman55
This can also be used as a color randomizer but it can also be done by simpler methods. Really nice tutorial, perfectly explained! (+rep)
Image
User avatar
MrAksel
C# Coder
C# Coder
Posts: 1758
Joined: Fri Mar 26, 2010 12:27 pm

Re: How to use System.Random
MrAksel
Thanks for the comment
LMAOSHMSFOAIDMT
Laughing my a** of so hard my sombrero fell off and I dropped my taco lmao;


Over 30 projects with source code!
Please give reputation to helpful members!

Image
Image
3 posts Page 1 of 1
Return to “Tutorials”