0

I have 2 classes; a main class and a Person class. Each Person has a few properties, including name, age, and gender. I have a method inside this Person class, randomName() which chooses a random first and last name from a set list. To choose a random name, I first create a Random object. I then select 2 random integers and use these integers to select a random name. My problem arises when I try and create 2 Person objects inside my main class - they both have the same name. I have narrowed the problem down to my Person class randomName() method using the exact same integers each time I call the method. Why is it doing this?

class Person
{
  public string Firstname { get; set; }
  public string Surname { get; set; }
  public string Gender { get; set; }

  public void randomName()
  {
    string[] names = { ... }; // array of possible names 

    Random rand = new Random();
    int a = rand.Next(names.Length - 1); // length of names array

    string name = names[a]; // grab random name

    Console.WriteLine(name);
  }
}

class Main
{
  public Main()
  {
    Person a = new Person();
    a.randomName();

    Person b = new Person();
    b.randomName();

    // These 2 Person objects have the exact same name every single time
  }
}

Edit: solved
I made the mistake of thinking that I could create multiple Random objects within a couple of milliseconds, believing that this would create completely different random seeds. I was wrong.

Lachlan Mather
  • 273
  • 1
  • 5
  • 16
  • Move `Random rand = new Random();` out of method, do not *recreate* the `Random`: `private static Random rand = new Random();` – Dmitry Bychenko Jun 07 '19 at 10:44
  • @DmitryBychenko Thank you, I did not realise that `Random` objects had to be created more than a couple of milliseconds apart. This has saved me a lot of trouble, thank you very much. – Lachlan Mather Jun 07 '19 at 10:48

0 Answers0