c# random

c# random

Here are very basic examples of getting Random number from given range using C#.net and Vb.net.

c#-Random

C#.net-example of Random number.

using System;
namespace Csharp.RandomExample
{
class Program
{
static void Main(string[] args)
{
for (int i = 0; i <= 100; i++)
{
Console.WriteLine(GenerateRandomNumber());
}
Console.ReadLine();
}
static int GenerateRandomNumber()
{
Random randomNumber = new Random();
return randomNumber.Next();
}
}
}
Output
1191950499
2074875102
2074875102
2074875102
2074875102
2074875102
2074875102
2074875102
2074875102
2074875102
Description

As you can see in the output above the numbers are not different for many times. This is because the seed for Random numbers is based on System Clock if the loop is faster than system clock tick, the same seed will be used for generating the number and you get same number.

(VB.net) Random example

Namespace Csharp.RandomExample
Class Program
Private Shared Sub Main(args As String())
For i As Integer = 0 To 100
Console.WriteLine(GenerateRandomNumber())
Next
Console.ReadLine()
End Sub
Private Shared Function GenerateRandomNumber() As Integer
Dim randomNumber As New Random()
Return randomNumber.[Next]()
End Function
End Class
End Namespace

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5