Does linqpad reuse the random seed between queries

s952163 :

For this code:

void Main()
{
    var testRandom = new TestRandom();
    testRandom.RandGen.Dump("Property1");
    testRandom.RandGen.Dump("Property2");
    TestRandom.rngStatic.Dump("Static field1");
    TestRandom.rngStatic.Dump("Static field2");
    testRandom.rngInstance.Dump("Instance field1");
    testRandom.rngInstance.Dump("Instance field2");
}

// Define other methods, classes and namespaces here

class TestRandom
{
    private static Random _rnd = new System.Random();
    public static int rngStatic = _rnd.Next();
    public int rngInstance = _rnd.Next();
    public int RandGen =>  _rnd.Next();
}

I get the following result in LinqPad:

Property1 167577867

Property2 2076433106

Static field1 1758463813

Static field2 1758463813

Instance field1 1875178546

Instance field2 1875178546

Static Field 1 and 2, Instance Field 1 and 2 show the same random number when run in the same query. This is as expected, however even when I re-run the query, Instance Field 1 and 2 will keep showing the same random number as in previous runs. So I suspect the seed is fixed, but couldn't confirm it.

Second Query run:

Property1 1860313679

Property2 1472007479

Static field1 1758463813

Static field2 1758463813

Instance field1 1370753000

Instance field2 1370753000

Thomas Weller :

No. Why should LinqPad have a special handling for random numbers that makes it incompatible with other applications?

It will compile each query into a separate assembly and initialize the static variables only once. In order to unload the assembly, it would need to destroy the AppDomain which contains the assembly.

Thus, it could also have been possible that it creates an AppDomain per query and re-uses that AppDomain for subsequent runs. But with a check of AppDomain.CurrentDomain, that does not seem to be the case. So we have 1 AppDomain and multiple assemblies.

You can confirm this by putting a Console.WriteLine("Test"); into the code so that it needs recompilation. You'll get a new number.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=368743&siteId=1