Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations John Tel on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

generating random numbers

Status
Not open for further replies.

mp89

Programmer
Sep 17, 2004
35
GB
I have a method that I am using to generate random numbers using Random.Next. However, every time I call the method I get the same random number. Is there a C# equivalent of Randomize is VB6?


Thanks,

Mike

 
There is no C# equivalent to Randomize in VB. As a language C# doesn't have built in methods in the same way. You should be able to use the Framework classes to generate random numbers as you suggested. The following Console app generates 10 random numbers just fine
Code:
using System;

namespace RandomNum
{
	/// <summary>
	/// Summary description for Class1.
	/// </summary>
	class Class1
	{
		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main(string[] args)
		{
			Random random =new Random();
			for(int i=0; i<10; i++) {
				Console.WriteLine(random.Next());
			}
		}
	}
}
Could you be experiencign soem kind of caching if your using ASP.NET?

Rob

Every gun that is made, every warship launched, every rocket fired, signifies in the final sense a theft from those who hunger and are not fed, those who are cold and are not clothed - Eisenhower 1953
 
Use a seed value that is dependent on time to produce different random sequences.
Code:
Random random1 = new Random((int)DateTime.Now.Ticks));
If that is not enough bacause your code run on a fast computer and then the clock might not have time to change, use the following constructor for the next sequence:
Code:
Random random2 = new Random(~(int)DateTime.Now.Ticks)); // bitwise operator
So , alternating the above constructors you should never have the same sequence.
-obislavu-
 
For really strong random numbers, you can use the crypto libraries:
Code:
using System.Security.Cryptography;

RNGCryptoServiceProvider rng = New RNGCryptoServiceProvider();

byte[] ra = new Byte[500];
rng.GetBytes(ra);
// ra now has 500 strong random bytes

// Take first 4 bytes and convert to a 32-bit integer
int randValue = BitConverter.ToInt32(ra, 0);
Chip H.


____________________________________________________________________
If you want to get the best response to a question, please read FAQ222-2244 first
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top