Search code examples
c#randomvb6vb6-migration

What is the C# equivalent of this VB6 Rnd() call?


I am having a problem with the VB code Int(Rnd() * 75) + 75) conveting it to C#. I have tried

Random random = new Random
random.Next( 75 ) + 75

But its isnt right. Please Help me.

Thanks


Solution

  • Assuming that's meant to give a value between 75 (inclusive) and 150 (exclusive) I'd use

    Random random = new Random();
    int value = random.Next(75, 150);
    

    That's clearer than first generating a number in the range [0, 75) and then adding 75, IMO.

    Note, however, that you shouldn't be creating a new instance of Random every time you want a random number. You probably want one instance per thread. I have a reasonably long article explaining the various pitfalls in generating random numbers, and some workarounds.