random always the same.

A

ad

I write a function below the generate a alpha, but when I call it , it
always return 'b'
How can I do generate a character randomly.


public static char CharRnd()
{
Random rnd = new Random();

char c = (char)rnd.Next('a', 'z' + 1);
return c;
}
 
X

xhy_China

you must set seed. change the code as follows.
public static char CharRnd()
{
// Random rnd = new Random();

Random rd = new Random(DateTime.Now.Ticks);
 
J

Jon Skeet [C# MVP]

xhy_China said:
you must set seed. change the code as follows.

// Random rnd = new Random();

Random rd = new Random(DateTime.Now.Ticks);

The parameterless constructor for Random already uses the current
date/time as a seed. The key is to create a single instance of Random
and use that repeatedly.
 
P

Peter Kirk

Jon Skeet said:
The parameterless constructor for Random already uses the current
date/time as a seed. The key is to create a single instance of Random
and use that repeatedly.

But why would the sequence of random numbers be the same for each instance
of Random? Does that mean the OP instantiated all his Random objects
simultaneously (and they therefore had the same date-time seed)?
 
C

Christof Nordiek

Peter Kirk said:
But why would the sequence of random numbers be the same for each instance
of Random? Does that mean the OP instantiated all his Random objects
simultaneously (and they therefore had the same date-time seed)?
Or within 100 ns (= 1 Tick) ;). In the time of GHz-proceccors this should be
possible (depending on what he does in the meantime). The resolution of
DateTime.Now is even less. Wich resolution the parameterless constructor for
Random uses i don't know, but I suppose it's one of these values.
 
J

Jon Skeet [C# MVP]

Peter Kirk said:
But why would the sequence of random numbers be the same for each instance
of Random? Does that mean the OP instantiated all his Random objects
simultaneously (and they therefore had the same date-time seed)?

"Simultaneously" can be pretty loose - it really means "within the time
period it takes for DateTime.Now to change" which can be a long time in
computing terms.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top