0

i have 2 child class and 1 mother class. i defined a rand object in mother and i called it in childs but its doesn't work properly. both int are the same. i want to assign different value

 class Mother
    {
        public int sayi;
        public Random rand = new Random();

        static void Main(string[] args)
        {
            ChildFirst firsCh = new ChildFirst();
            ChildSecond secondCh = new ChildSecond();

            Console.ReadKey();
        }
    }
    class ChildFirst : Mother
    { public ChildFirst() { sayi = rand.Next(1, 100); Console.WriteLine("Random int is: " + sayi); } }
    class ChildSecond : Mother
    { public ChildSecond() { sayi = rand.Next(1, 100); Console.WriteLine("Random int is: " + sayi); } }
  • 1
    You are initializing two instances of the Random class at the same time, therefore they both has the same seed and will generate the same pseudo random sequence. – Zohar Peled Apr 03 '20 at 18:33
  • i use a function that returns a int, instead of a int. public Random rand = new Random(); public int sayi() { return rand.Next(1,100); } – MUSTAFA CELAL GÜLER Apr 03 '20 at 18:43
  • `ChildFirst firsCh = new ChildFirst(); ChildSecond secondCh = new ChildSecond();` that's in the code you've posted. these lines happen so fast the computer's timer don't change between them and therefor both instances of `Random` has the same seed. – Zohar Peled Apr 03 '20 at 19:03

0 Answers0