To generate random numbers in csharp or vb.net you simply need to use the Random class which is located in the namespace System.

c# example

var rand = new Random();
int randInt1 = rand.Next(1, 10);
int randInt2 = rand.Next(10); 

vb.net example

Dim rand = New Random()
Dim randInt1 As Integer = rand.Next(1, 10)
Dim randInt2 As Integer = rand.Next(10)

remember that the first rand.Next statements will return a number between 1 and 9 while the second rand.Next statement will return a number between 0 and 9.

 

Tip

If you do new Random() in a Loop the Random is initialised again and again, your Random function can then possibly return the same number several times.
You should keep a single Random instance and keep using Next on it without reinitialising.

Leave a Reply