class Student
{
private string FirstName { get; set; }
private string LastName { get; set; }
private int age { get; set; }
private int studentID { get; set; }
private static int count = 0;
**static Random randomNumber = new Random(); // works**
**Random randomNumber = new Random(); // doesn't work I get the same studentID number**
public Student()// constructor
{
this.studentID = randomNumber.Next(1000000, 100000000);
count++;
Console.WriteLine("count {0} studentID {1}", count, studentID);
}
public Student(string first, string last, int age)
{
this.studentID = randomNumber.Next(1000000, 100000000);
count++;
Console.WriteLine("count {0} studentID {1}", count, studentID);
this.FirstName = first;
this.LastName = last;
this.age = age;
}
...... continuation
a few get methods
...... continuation
public void PrintData()
{
Console.WriteLine("Name is {0}, Lastname is {1} , Age is {2} , studentID is {3}", FirstName, LastName, age, this.studentID);
}
Why do I keep getting the same number , but if I make the Random object static it generates/assigns new number. Not sure where my logic is faulty.
If you you keep creating new Random objects in the constructor it will reset the seed (If you don’t supply arguments the seed is set to the current time (See: MSDN: Random constructor) – so if you create multiple Random objects very near each other (in time) then it will have the same seed). Since Random is not truely random (if you init it from the same seed you’ll always get the same sequence back) you will get the same numbers back in the non-static version. The static version is created only once and you keep asking it for the next number in the sequence, hence it appears to give you actual random numbers.