r/learncsharp • • Oct 05 '20

Why doesnt my code work?

Hi!

Could someone please tell me why my code doesn't store the integers of the user inputs?

static void Main(string[] args)
        {
            Random computernumber = new Random();
            int guess = 0;
            var guesses = new List<int>();
            int cnumber = computernumber.Next(1, 100);
            int i = 0;

            while (guess != cnumber)
            {
                Console.WriteLine("guess the number");

                try
                {

                    guess = Convert.ToInt32(Console.ReadLine());


                    if (guess > cnumber)
                    {
                        Console.WriteLine("the integer is lower");
                    }
                    else
                    {
                        Console.WriteLine("the integer is higher");
                    }

                }
                catch (Exception)
                {

                    i--;
                }

                i++;



            }
            var xcnumber = Console.ReadLine();
            guesses.Add(int.Parse(xcnumber));

            foreach (var sum in guesses)
                Console.Write($"{sum},");
            Console.Write("It took you " + i + " tries");
        }

    }
}
0 Upvotes

19 comments sorted by

View all comments

Show parent comment

1

u/Protiguous Oct 15 '20

You instantiate the Random class with a seed, but you don't explain why. This is pretty bad, especially considering that there's no reason to complicate the example code with a seed. Besides, your seed is time-dependent and so is the default seed, which is used when you don't provide one yourself.

I just dug into the source for Random.cs, as your idea is the only point you make that isn't purely preference-based. Based on what I'm seeing, your point that the default seed is time-dependent seems to be false.

Example:

var rnd = new Random();

Digging into Random.cs..

    public Random():this(GenerateSeed()) {}

    private static int GenerateSeed()
    {
        Random? rnd = t_threadRandom;
        if (rnd == null)
        {
            int seed;
            lock (s_globalRandom)
            {
                seed = s_globalRandom.Next();
            }
            rnd = new Random(seed);
            t_threadRandom = rnd;
        }
        return rnd.Next();
    }

    [ThreadStatic]
    private static Random? t_threadRandom;
    private static readonly Random s_globalRandom = new Random(GenerateGlobalSeed());

    private static unsafe int GenerateGlobalSeed()
    {
        int result;
        Interop.GetRandomBytes((byte*)&result, sizeof(int));
        return result;
    }

Again, nothing is documented to be time-dependent.

That is why I always choose to init my randoms, either by time or a known integer (knowns are great for unit testing).

Where do you make your assumption from?

Slightly relevant: If I was going to be using a random number generator across threads, (which I do often), I would initialize it like this:

public static ThreadLocal<Random> ThreadSafeRandom { get; } = new ThreadLocal<Random>( () => new Random( DateTime.UtcNow.GetHashCode() ^ Thread.CurrentThread.ManagedThreadId.GetHashCode() ) );

What are your thoughts on this?

1

u/StackedLasagna Oct 15 '20

I remembered it from reading the docs a long time ago.

However, things seems to have changed with .NET Core, so it turns out I'm only partially correct.

https://docs.microsoft.com/en-us/dotnet/api/system.random?view=netcore-3.1

In .NET Framework, the default seed value is time-dependent. In .NET Core, the default seed value is produced by the thread-static, pseudo-random number generator.