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

Tags:

c# randomC# Get Random Item From List (VB.net) Example.C# foreach loopc# stringc# arraylistC# XML XmlReaderC# DateTime DifferenceC# Binary To StringC# Regular Expression Get Text Between BracketsC# For LoopReplace string in C#

Author

My name is Satalaj, but people call me Sat. Here is my homepage: . I live in Pune, PN and work as a Software Engineer. I'm former MVP in ASP.net year 2010.
Disclaimer: Views or opinion expressed here are my personal research and it has nothing to do with my employer. You are free to use the code, ideas/hints in your projects. However, you should not copy and paste my original content to other web sites. Feel free to copy or extend the code.
If you want to fight with me, this website is not for you.
 

I'm Satalaj.