1

My point in this code is to create some random dates(should be simple) but...

static void Main(string[] args) {
    Console.WriteLine(CreateDate());
    Console.WriteLine(CreateDate());
    Console.WriteLine(CreateDate());
}

public static DateTime CreateDate() {
    Random rnd = new Random();
    DateTime date = new DateTime(1990, 1, 1);

    date = date.AddDays(rnd.Next(30));
    date = date.AddMonths(rnd.Next(11));
    date = date.AddYears(rnd.Next(28));

    return date;
}

The output allways the same... What am I missing?

The date doesn't change whatever I do.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • 6
    You only need one instance of the Random class. Creating new instances is likely to happen in the same instance of time, so the same values are produced. – Andy G Dec 28 '17 at 14:44
  • 5
    `new Random()` initializes the `Random` class with the current time as seed. Since you create the `Random` with each call again **with the same seed** the random values are the same (and so not very random). – René Vogt Dec 28 '17 at 14:44

2 Answers2

4

You need to move random object out of method.

All Random instances seeded with same default value (derived by system clock, due to being in close succession coupled with finite resolution), and will yield same result ( on random.Next() call).

The Random() constructor uses the system clock to provide a seed value. This is the most common way of instantiating the random number generator.

If the same seed is used for separate Random objects, they will generate the same series of random numbers. This can be useful for creating a test suite that processes random values, or for replaying games that derive their data from random numbers. However, note that Random objects in processes running under different versions of the .NET Framework may return different series of random numbers even if they're instantiated with identical seed values.

From official msdn documentation https://msdn.microsoft.com/en-us/library/system.random.aspx.

Tilak
  • 30,108
  • 19
  • 83
  • 131
  • 2
    Probably this quote fits better for this question? > The default seed value is derived from the system clock and has finite resolution. As a result, different Random objects that are created in close succession by a call to the default constructor will have identical default seed values – zc246 Dec 28 '17 at 14:49
2

You keep creating new Random, which leads to making the same sequence of pseudo-random numbers.

Create Random once, and pass it to CreateDate:

// Inside Main()
var rnd = new Random();
Console.WriteLine(CreateDate(rnd));
Console.WriteLine(CreateDate(rnd));
Console.WriteLine(CreateDate(rnd));
...
// Change method signature
public static DateTime CreateDate(Random rnd) {
    DateTime date = new DateTime(1990, 1, 1);
    ... // The rest of the method remains the same
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523