User Id :    Password :      New Member   Forgot Password  
 
how to generate random number in csharp
Description Here I will show how to generate random number in csharp.   No. of Views     5619
  Rating     4
Author Najmul Hoda   Posted On     18 Oct 2010
Tags ASP.NET,C#    

Sample Code   Download Code

In this code snippet I will show you how to generate random number in csharp.

CSharp has a Random() class that generated random number between 2 numbers.

Code

public int GetRandomNumber(int min, int max)
{
Random random = new Random();
return random.Next(min, max); 
}


The above function will generate a random number between min and max values supplied. To show random number I have called GetRandomNumber()  in loop in ShowRandonNumber() method below.


public void ShowRandonNumber()
{
for (int count=0;count<5;count++)
Response.Write(GetRandomNumber(5, 20));
}

Enjoy coding...........

About Author

About Author He is a team lead, having 8+ years of experience. He loves writing technical article for .Net developers. Najmul Hoda
No Photo
 
Country United States
Company BirlaSoft
Home Page http://www.magixchat.com

Rate this article

Rating options from poor, fair, good, very good to excelent.  
 

Comments

 
 
Posted By Najmul Hoda on 25 Oct 2010 at 12:52 AM
 
Yes James. You are right. Creating a random number at each step is not a good idea. It consumes memory as well as CPU time increases. Thanks for the advice.
 
 
 
Posted By James Curran on 22 Oct 2010 at 01:43 PM
 
That has a couple problems. Mainly, you create a new Random object every time you want a new random number. Creating a Random object is a fairly expensive operation, which is why it was designed in a way so that you could creat it once, and then use it multiple times after that. But that merely makes you code slow. There is a much bigger problem which you should see it you run ShowRandonNumber() several times. Generally, it will print the same number 5 times, on each run. What is happening is that when you create a Random object without giving it a seed, it is seeded using the current time in milliseconds, which means if you create two Random objects within the same millisecond (quite likely in a tight loop like that), both objects will be initialized with the same seed and will product the same sequence of random numbers. To fix both problems, pull the `random` out of the function, and make it a static: static readonly Random random = new Random(); public int GetRandomNumber(int min, int max) { return random.Next(min, max); }
 
 
   
Write your comment here.
Comment
Verification Code