Random number generator only generating one random number












695















I have the following function:



//Function to get random number
public static int RandomNumber(int min, int max)
{
Random random = new Random();
return random.Next(min, max);
}


How I call it:



byte mac = new byte[6];
for (int x = 0; x < 6; ++x)
mac[x] = (byte)(Misc.RandomNumber((int)0xFFFF, (int)0xFFFFFF) % 256);


If I step that loop with the debugger during runtime I get different values (which is what I want).
However, if I put a breakpoint two lines below that code, all members of the "mac" array have equal value.



Why does that happen?










share|improve this question




















  • 15





    using new Random().Next((int)0xFFFF, (int)0xFFFFFF) % 256); doesn't yield any better "random" numbers than .Next(0, 256)

    – bohdan_trotsenko
    Mar 18 '16 at 13:16











  • You may find this NuGet package helpful. It provides a static Rand.Next(int, int) method which provides static access to random values without locking or running into the seed re-use problem

    – ChaseMedallion
    May 7 '16 at 16:09
















695















I have the following function:



//Function to get random number
public static int RandomNumber(int min, int max)
{
Random random = new Random();
return random.Next(min, max);
}


How I call it:



byte mac = new byte[6];
for (int x = 0; x < 6; ++x)
mac[x] = (byte)(Misc.RandomNumber((int)0xFFFF, (int)0xFFFFFF) % 256);


If I step that loop with the debugger during runtime I get different values (which is what I want).
However, if I put a breakpoint two lines below that code, all members of the "mac" array have equal value.



Why does that happen?










share|improve this question




















  • 15





    using new Random().Next((int)0xFFFF, (int)0xFFFFFF) % 256); doesn't yield any better "random" numbers than .Next(0, 256)

    – bohdan_trotsenko
    Mar 18 '16 at 13:16











  • You may find this NuGet package helpful. It provides a static Rand.Next(int, int) method which provides static access to random values without locking or running into the seed re-use problem

    – ChaseMedallion
    May 7 '16 at 16:09














695












695








695


147






I have the following function:



//Function to get random number
public static int RandomNumber(int min, int max)
{
Random random = new Random();
return random.Next(min, max);
}


How I call it:



byte mac = new byte[6];
for (int x = 0; x < 6; ++x)
mac[x] = (byte)(Misc.RandomNumber((int)0xFFFF, (int)0xFFFFFF) % 256);


If I step that loop with the debugger during runtime I get different values (which is what I want).
However, if I put a breakpoint two lines below that code, all members of the "mac" array have equal value.



Why does that happen?










share|improve this question
















I have the following function:



//Function to get random number
public static int RandomNumber(int min, int max)
{
Random random = new Random();
return random.Next(min, max);
}


How I call it:



byte mac = new byte[6];
for (int x = 0; x < 6; ++x)
mac[x] = (byte)(Misc.RandomNumber((int)0xFFFF, (int)0xFFFFFF) % 256);


If I step that loop with the debugger during runtime I get different values (which is what I want).
However, if I put a breakpoint two lines below that code, all members of the "mac" array have equal value.



Why does that happen?







c# random






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 22 '17 at 16:19









Taryn

192k47292356




192k47292356










asked Apr 20 '09 at 12:11









Ivan ProdanovIvan Prodanov

14.7k63152236




14.7k63152236








  • 15





    using new Random().Next((int)0xFFFF, (int)0xFFFFFF) % 256); doesn't yield any better "random" numbers than .Next(0, 256)

    – bohdan_trotsenko
    Mar 18 '16 at 13:16











  • You may find this NuGet package helpful. It provides a static Rand.Next(int, int) method which provides static access to random values without locking or running into the seed re-use problem

    – ChaseMedallion
    May 7 '16 at 16:09














  • 15





    using new Random().Next((int)0xFFFF, (int)0xFFFFFF) % 256); doesn't yield any better "random" numbers than .Next(0, 256)

    – bohdan_trotsenko
    Mar 18 '16 at 13:16











  • You may find this NuGet package helpful. It provides a static Rand.Next(int, int) method which provides static access to random values without locking or running into the seed re-use problem

    – ChaseMedallion
    May 7 '16 at 16:09








15




15





using new Random().Next((int)0xFFFF, (int)0xFFFFFF) % 256); doesn't yield any better "random" numbers than .Next(0, 256)

– bohdan_trotsenko
Mar 18 '16 at 13:16





using new Random().Next((int)0xFFFF, (int)0xFFFFFF) % 256); doesn't yield any better "random" numbers than .Next(0, 256)

– bohdan_trotsenko
Mar 18 '16 at 13:16













You may find this NuGet package helpful. It provides a static Rand.Next(int, int) method which provides static access to random values without locking or running into the seed re-use problem

– ChaseMedallion
May 7 '16 at 16:09





You may find this NuGet package helpful. It provides a static Rand.Next(int, int) method which provides static access to random values without locking or running into the seed re-use problem

– ChaseMedallion
May 7 '16 at 16:09












9 Answers
9






active

oldest

votes


















954














Every time you do new Random() it is initialized using the clock. This means that in a tight loop you get the same value lots of times. You should keep a single Random instance and keep using Next on the same instance.



//Function to get a random number 
private static readonly Random random = new Random();
private static readonly object syncLock = new object();
public static int RandomNumber(int min, int max)
{
lock(syncLock) { // synchronize
return random.Next(min, max);
}
}




Edit (see comments): why do we need a lock here?



Basically, Next is going to change the internal state of the Random instance. If we do that at the same time from multiple threads, you could argue "we've just made the outcome even more random", but what we are actually doing is potentially breaking the internal implementation, and we could also start getting the same numbers from different threads, which might be a problem - and might not. The guarantee of what happens internally is the bigger issue, though; since Random does not make any guarantees of thread-safety. Thus there are two valid approaches:




  • synchronize so that we don't access it at the same time from different threads

  • use different Random instances per thread


Either can be fine; but mutexing a single instance from multiple callers at the same time is just asking for trouble.



The lock achieves the first (and simpler) of these approaches; however, another approach might be:



private static readonly ThreadLocal<Random> appRandom
= new ThreadLocal<Random>(() => new Random());


this is then per-thread, so you don't need to synchronize.






share|improve this answer





















  • 13





    As a general rule, all static methods should be made thread-safe, since it is hard to guarantee that multiple threads won't call it at the same time. It is not usually necessary to make instance (i.e. non-static) methods thread-safe.

    – Marc Gravell
    Apr 20 '09 at 12:32






  • 3





    @Florin - there is no difference re "stack based" between the two. Static fields are just as much "external state", and will absolutely be shared between callers. With instances, there is a good chance that different threads have different instances (a common pattern). With statics, it is guaranteed that they all share (not including [ThreadStatic]).

    – Marc Gravell
    Apr 20 '09 at 13:03






  • 2





    @MarcGravell with the ThreadLocal approach is there not still the risk of two threads generating the same sequence if appRandom is accessed at the same time by those two threads? Or does some attribute of the thread contribute to the generated sequence?

    – Pero P.
    Aug 9 '12 at 20:38








  • 5





    @Dan if the object is never exposed publicly: you can. The (very theoretical) risk is that some other thread is locking on it in ways you did not expect.

    – Marc Gravell
    Jan 31 '14 at 22:34






  • 2





    @smiron It's very likely you're simply using the random outside of a lock as well. Locking doesn't prevent all access to what you're locking around - it just makes sure that two lock statements on the same instance will not run concurrently. So lock (syncObject) will only help if all random.Next() calls are also within lock (syncObject). If the scenario you describe does happen even with correct lock usage, it also extremely likely happens in a single-threaded scenario (e.g. Random is subtly broken).

    – Luaan
    Apr 21 '15 at 12:17



















106














For ease of re-use throughout your application a static class may help.



public static class StaticRandom
{
private static int seed;

private static ThreadLocal<Random> threadLocal = new ThreadLocal<Random>
(() => new Random(Interlocked.Increment(ref seed)));

static StaticRandom()
{
seed = Environment.TickCount;
}

public static Random Instance { get { return threadLocal.Value; } }
}


You can use then use static random instance with code such as



StaticRandom.Instance.Next(1, 100);





share|improve this answer

































    57














    Mark's solution can be quite expensive since it needs to synchronize everytime.



    We can get around the need for synchronization by using the thread-specific storage pattern:




    public class RandomNumber : IRandomNumber
    {
    private static readonly Random Global = new Random();
    [ThreadStatic] private static Random _local;

    public int Next(int max)
    {
    var localBuffer = _local;
    if (localBuffer == null)
    {
    int seed;
    lock(Global) seed = Global.Next();
    localBuffer = new Random(seed);
    _local = localBuffer;
    }
    return localBuffer.Next(max);
    }
    }



    Measure the two implementations and you should see a significant difference.






    share|improve this answer



















    • 11





      Locks are very cheap when they aren't contested... and even if contested I would expect the "now do something with the number" code to dwarf the cost of the lock in most interesting scenarios.

      – Marc Gravell
      Sep 18 '09 at 15:57






    • 4





      Agreed, this solves the locking problem, but isn't this still a highly complicated solution to a trivial problem: that you need to write ''two'' lines of code to generate a random number instead of one. Is this really worth it to save reading one simple line of code?

      – EMP
      Apr 15 '10 at 23:07






    • 4





      +1 Using an additional global Random instance for getting the seed is a nice idea. Note also that the code can be further simplified using the ThreadLocal<T> class introduced in .NET 4 (as Phil also wrote below).

      – Groo
      May 9 '14 at 8:41





















    35














    My answer from here:



    Just reiterating the right solution:



    namespace mySpace
    {
    public static class Util
    {
    private static rnd = new Random();
    public static int GetRandom()
    {
    return rnd.Next();
    }
    }
    }


    So you can call:



    var i = Util.GetRandom();


    all throughout.



    If you strictly need a true stateless static method to generate random numbers, you can rely on a Guid.



    public static class Util
    {
    public static int GetRandom()
    {
    return Guid.NewGuid().GetHashCode();
    }
    }


    It's going to be a wee bit slower, but can be much more random than Random.Next, at least from my experience.



    But not:



    new Random(Guid.NewGuid().GetHashCode()).Next();


    The unnecessary object creation is going to make it slower especially under a loop.



    And never:



    new Random().Next();


    Not only it's slower (inside a loop), its randomness is... well not really good according to me..






    share|improve this answer





















    • 7





      I do not agree with the Guid case. The Random class implements a uniform distribution. Which is not the case in Guid. Guid aim is to be unique not uniformly distributed (and its implementation is most of the time based on some hardware/machine property which is the opposite of ... randomness).

      – Askolein
      Mar 31 '13 at 13:37






    • 3





      if you cannot prove the uniformity of Guid generation , then it is wrong to use it as random (and the Hash would be another step away from uniformity). Likewise, collisions aren't an issue: uniformity of collision is. Concerning the Guid generation not being on hardware anymore I'm going to RTFM, my bad (any reference?)

      – Askolein
      Mar 31 '13 at 14:18








    • 5





      There is two understandings of "Random": 1. lack of pattern or 2. lack of pattern following an evolution described by a probability distribution (2 included in 1). Your Guid example is correct in case 1, not in case 2. In opposite: Random class matches case 2 (thus, case 1 too). You can only replace the usage of Random by your Guid+Hash if you are not in case 2. Case 1 is probably enough to answer the Question, and then, your Guid+Hash works fine. But it is not clearly said (ps: this uniform)

      – Askolein
      Mar 31 '13 at 17:33






    • 2





      @Askolein Just for some test data, I run several batches of both Random and Guid.NewGuid().GetHashCode() through Ent (fourmilab.ch/random) and both are similarly random. new Random(Guid.NewGuid().GetHashCode()) works just as well, as does using a synchronized "master" Random to generate seeds for "child" Randoms.. Of course, it does depend on how your system generates Guids - for my system, they are quite random, and on others it may even be crypto-random. So Windows or MS SQL seems fine nowadays. Mono and/or mobile might be different, though.

      – Luaan
      Apr 21 '15 at 12:29






    • 2





      @EdB As I have said in comments previously, while Guid (a large number) is meant to be unique, the GetHashCode of the Guid in .NET is derived from its string representation. The output is quite random for my liking.

      – nawfal
      Aug 3 '15 at 17:28



















    23














    I would rather use the following class to generate random numbers:



    byte random;
    System.Security.Cryptography.RNGCryptoServiceProvider prov = new System.Security.Cryptography.RNGCryptoServiceProvider();
    prov.GetBytes(random);





    share|improve this answer





















    • 30





      I'm not one of the down-voters, but note that standard PNRG do serve a genuine need - i.e. to be able to repeatably reproduce a sequence from a known seed. Sometimes the sheer cost of a true cryptographic RNG is too much. And sometimes a crypto RNG is necessary. Horses for courses, so to speak.

      – Marc Gravell
      Apr 20 '09 at 12:35






    • 4





      According to the documentation this class is thread-safe, so that's something in it's favour.

      – Rob Church
      Apr 26 '13 at 13:51











    • What is the probability two random strings to be one and the same using that? If the string is just 3 characters I guess this will happen with high probability but what if is 255 characters length is it possible to have the same random string or is guaranteed that this can't happen from the algorithm?

      – Lyubomir Velchev
      Jul 12 '16 at 13:03



















    13














    1) As Marc Gravell said, try to use ONE random-generator. It's always cool to add this to the constructor: System.Environment.TickCount.



    2) One tip. Let's say you want to create 100 objects and suppose each of them should have its-own random-generator (handy if you calculate LOADS of random numbers in a very short period of time). If you would do this in a loop (generation of 100 objects), you could do this like that (to assure fully-randomness):



    int inMyRandSeed;

    for(int i=0;i<100;i++)
    {
    inMyRandSeed = System.Environment.TickCount + i;
    .
    .
    .
    myNewObject = new MyNewObject(inMyRandSeed);
    .
    .
    .
    }

    // Usage: Random m_rndGen = new Random(inMyRandSeed);


    Cheers.






    share|improve this answer





















    • 3





      I would move System.Environment.TickCount out of the loop. If it ticks over while you are iterating then you will have two items initialized to the same seed. Another option would be to combine the tickcount an i differently (e.g. System.Environment.TickCount<<8 + i)

      – Dolphin
      Jun 25 '09 at 19:03











    • If I understand correctly: do you mean, it could happen, that "System.Environment.TickCount + i" could result the SAME value?

      – sabiland
      Jun 26 '09 at 13:18











    • EDIT: Of course, no need to have TickCount inside the loop. My bad :).

      – sabiland
      Jun 26 '09 at 13:19






    • 2





      The default Random() constructor calls Random(Environment.TickCount) anyway

      – Alsty
      Feb 16 '17 at 16:29



















    2














    Every time you execute



    Random random = new Random (15);


    It does not matter if you execute it millions of times, you will always use the same seed.



    If you use



    Random random = new Random ();


    You get different random number sequence, if a hacker guesses the seed and your algorithm is related to the security of your system - your algorithm is broken. I you execute mult. In this constructor the seed is specified by the system clock and if several instances are created in a very short period of time (milliseconds) it is possible that they may have the same seed.



    If you need safe random numbers you must use the class




    System.Security.Cryptography.RNGCryptoServiceProvider




    public static int Next(int min, int max)
    {
    if(min >= max)
    {
    throw new ArgumentException("Min value is greater or equals than Max value.");
    }
    byte intBytes = new byte[4];
    using(RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
    {
    rng.GetNonZeroBytes(intBytes);
    }
    return min + Math.Abs(BitConverter.ToInt32(intBytes, 0)) % (max - min + 1);
    }


    Usage:



    int randomNumber = Next(1,100);





    share|improve this answer


























    • It does not matter if you execute it millions of times, you will always use the same seed. That's not true unless you specify the seed yourself.

      – LarsTech
      Oct 19 '18 at 17:47











    • Fixed up. Thanks Exactly as you say LarsTech, if the same seed is always specified, the same sequence of random numbers will always be generated. In my answer I refer to the constructor with parameters if you always use the same seed. The Random class generates only pseudo random numbers. If someone finds out what seed you have used in your algorithm, it can compromise the security or randomness of your algorithm. With the RNGCryptoServiceProvider class, you can safely have random numbers. I already corrected, thank you very much for the correction.

      – Joma
      Oct 19 '18 at 21:03



















    2














    just declare the Random class variable like this:



        Random r = new Random();
    // ... Get three random numbers.
    // Here you'll get numbers from 5 to 9
    Console.WriteLine(r.Next(5, 10));


    if you want to get different random number each time from your list then use



    r.Next(StartPoint,EndPoint) //Here end point will not be included


    Each time by declaring Random r = new Random() once.






    share|improve this answer

































      1














      There are a lot of solutions, here one: if you want only number erase the letters and the method receives a random and the result length.



      public String GenerateRandom(Random oRandom, int iLongitudPin)
      {
      String sCharacters = "123456789ABCDEFGHIJKLMNPQRSTUVWXYZ123456789";
      int iLength = sCharacters.Length;
      char cCharacter;
      int iLongitudNuevaCadena = iLongitudPin;
      String sRandomResult = "";
      for (int i = 0; i < iLongitudNuevaCadena; i++)
      {
      cCharacter = sCharacters[oRandom.Next(iLength)];
      sRandomResult += cCharacter.ToString();
      }
      return (sRandomResult);
      }





      share|improve this answer
























        protected by Community Aug 8 '14 at 13:28



        Thank you for your interest in this question.
        Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



        Would you like to answer one of these unanswered questions instead?














        9 Answers
        9






        active

        oldest

        votes








        9 Answers
        9






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        954














        Every time you do new Random() it is initialized using the clock. This means that in a tight loop you get the same value lots of times. You should keep a single Random instance and keep using Next on the same instance.



        //Function to get a random number 
        private static readonly Random random = new Random();
        private static readonly object syncLock = new object();
        public static int RandomNumber(int min, int max)
        {
        lock(syncLock) { // synchronize
        return random.Next(min, max);
        }
        }




        Edit (see comments): why do we need a lock here?



        Basically, Next is going to change the internal state of the Random instance. If we do that at the same time from multiple threads, you could argue "we've just made the outcome even more random", but what we are actually doing is potentially breaking the internal implementation, and we could also start getting the same numbers from different threads, which might be a problem - and might not. The guarantee of what happens internally is the bigger issue, though; since Random does not make any guarantees of thread-safety. Thus there are two valid approaches:




        • synchronize so that we don't access it at the same time from different threads

        • use different Random instances per thread


        Either can be fine; but mutexing a single instance from multiple callers at the same time is just asking for trouble.



        The lock achieves the first (and simpler) of these approaches; however, another approach might be:



        private static readonly ThreadLocal<Random> appRandom
        = new ThreadLocal<Random>(() => new Random());


        this is then per-thread, so you don't need to synchronize.






        share|improve this answer





















        • 13





          As a general rule, all static methods should be made thread-safe, since it is hard to guarantee that multiple threads won't call it at the same time. It is not usually necessary to make instance (i.e. non-static) methods thread-safe.

          – Marc Gravell
          Apr 20 '09 at 12:32






        • 3





          @Florin - there is no difference re "stack based" between the two. Static fields are just as much "external state", and will absolutely be shared between callers. With instances, there is a good chance that different threads have different instances (a common pattern). With statics, it is guaranteed that they all share (not including [ThreadStatic]).

          – Marc Gravell
          Apr 20 '09 at 13:03






        • 2





          @MarcGravell with the ThreadLocal approach is there not still the risk of two threads generating the same sequence if appRandom is accessed at the same time by those two threads? Or does some attribute of the thread contribute to the generated sequence?

          – Pero P.
          Aug 9 '12 at 20:38








        • 5





          @Dan if the object is never exposed publicly: you can. The (very theoretical) risk is that some other thread is locking on it in ways you did not expect.

          – Marc Gravell
          Jan 31 '14 at 22:34






        • 2





          @smiron It's very likely you're simply using the random outside of a lock as well. Locking doesn't prevent all access to what you're locking around - it just makes sure that two lock statements on the same instance will not run concurrently. So lock (syncObject) will only help if all random.Next() calls are also within lock (syncObject). If the scenario you describe does happen even with correct lock usage, it also extremely likely happens in a single-threaded scenario (e.g. Random is subtly broken).

          – Luaan
          Apr 21 '15 at 12:17
















        954














        Every time you do new Random() it is initialized using the clock. This means that in a tight loop you get the same value lots of times. You should keep a single Random instance and keep using Next on the same instance.



        //Function to get a random number 
        private static readonly Random random = new Random();
        private static readonly object syncLock = new object();
        public static int RandomNumber(int min, int max)
        {
        lock(syncLock) { // synchronize
        return random.Next(min, max);
        }
        }




        Edit (see comments): why do we need a lock here?



        Basically, Next is going to change the internal state of the Random instance. If we do that at the same time from multiple threads, you could argue "we've just made the outcome even more random", but what we are actually doing is potentially breaking the internal implementation, and we could also start getting the same numbers from different threads, which might be a problem - and might not. The guarantee of what happens internally is the bigger issue, though; since Random does not make any guarantees of thread-safety. Thus there are two valid approaches:




        • synchronize so that we don't access it at the same time from different threads

        • use different Random instances per thread


        Either can be fine; but mutexing a single instance from multiple callers at the same time is just asking for trouble.



        The lock achieves the first (and simpler) of these approaches; however, another approach might be:



        private static readonly ThreadLocal<Random> appRandom
        = new ThreadLocal<Random>(() => new Random());


        this is then per-thread, so you don't need to synchronize.






        share|improve this answer





















        • 13





          As a general rule, all static methods should be made thread-safe, since it is hard to guarantee that multiple threads won't call it at the same time. It is not usually necessary to make instance (i.e. non-static) methods thread-safe.

          – Marc Gravell
          Apr 20 '09 at 12:32






        • 3





          @Florin - there is no difference re "stack based" between the two. Static fields are just as much "external state", and will absolutely be shared between callers. With instances, there is a good chance that different threads have different instances (a common pattern). With statics, it is guaranteed that they all share (not including [ThreadStatic]).

          – Marc Gravell
          Apr 20 '09 at 13:03






        • 2





          @MarcGravell with the ThreadLocal approach is there not still the risk of two threads generating the same sequence if appRandom is accessed at the same time by those two threads? Or does some attribute of the thread contribute to the generated sequence?

          – Pero P.
          Aug 9 '12 at 20:38








        • 5





          @Dan if the object is never exposed publicly: you can. The (very theoretical) risk is that some other thread is locking on it in ways you did not expect.

          – Marc Gravell
          Jan 31 '14 at 22:34






        • 2





          @smiron It's very likely you're simply using the random outside of a lock as well. Locking doesn't prevent all access to what you're locking around - it just makes sure that two lock statements on the same instance will not run concurrently. So lock (syncObject) will only help if all random.Next() calls are also within lock (syncObject). If the scenario you describe does happen even with correct lock usage, it also extremely likely happens in a single-threaded scenario (e.g. Random is subtly broken).

          – Luaan
          Apr 21 '15 at 12:17














        954












        954








        954







        Every time you do new Random() it is initialized using the clock. This means that in a tight loop you get the same value lots of times. You should keep a single Random instance and keep using Next on the same instance.



        //Function to get a random number 
        private static readonly Random random = new Random();
        private static readonly object syncLock = new object();
        public static int RandomNumber(int min, int max)
        {
        lock(syncLock) { // synchronize
        return random.Next(min, max);
        }
        }




        Edit (see comments): why do we need a lock here?



        Basically, Next is going to change the internal state of the Random instance. If we do that at the same time from multiple threads, you could argue "we've just made the outcome even more random", but what we are actually doing is potentially breaking the internal implementation, and we could also start getting the same numbers from different threads, which might be a problem - and might not. The guarantee of what happens internally is the bigger issue, though; since Random does not make any guarantees of thread-safety. Thus there are two valid approaches:




        • synchronize so that we don't access it at the same time from different threads

        • use different Random instances per thread


        Either can be fine; but mutexing a single instance from multiple callers at the same time is just asking for trouble.



        The lock achieves the first (and simpler) of these approaches; however, another approach might be:



        private static readonly ThreadLocal<Random> appRandom
        = new ThreadLocal<Random>(() => new Random());


        this is then per-thread, so you don't need to synchronize.






        share|improve this answer















        Every time you do new Random() it is initialized using the clock. This means that in a tight loop you get the same value lots of times. You should keep a single Random instance and keep using Next on the same instance.



        //Function to get a random number 
        private static readonly Random random = new Random();
        private static readonly object syncLock = new object();
        public static int RandomNumber(int min, int max)
        {
        lock(syncLock) { // synchronize
        return random.Next(min, max);
        }
        }




        Edit (see comments): why do we need a lock here?



        Basically, Next is going to change the internal state of the Random instance. If we do that at the same time from multiple threads, you could argue "we've just made the outcome even more random", but what we are actually doing is potentially breaking the internal implementation, and we could also start getting the same numbers from different threads, which might be a problem - and might not. The guarantee of what happens internally is the bigger issue, though; since Random does not make any guarantees of thread-safety. Thus there are two valid approaches:




        • synchronize so that we don't access it at the same time from different threads

        • use different Random instances per thread


        Either can be fine; but mutexing a single instance from multiple callers at the same time is just asking for trouble.



        The lock achieves the first (and simpler) of these approaches; however, another approach might be:



        private static readonly ThreadLocal<Random> appRandom
        = new ThreadLocal<Random>(() => new Random());


        this is then per-thread, so you don't need to synchronize.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Aug 29 '17 at 6:45









        David Storfer

        16710




        16710










        answered Apr 20 '09 at 12:12









        Marc GravellMarc Gravell

        790k19521542557




        790k19521542557








        • 13





          As a general rule, all static methods should be made thread-safe, since it is hard to guarantee that multiple threads won't call it at the same time. It is not usually necessary to make instance (i.e. non-static) methods thread-safe.

          – Marc Gravell
          Apr 20 '09 at 12:32






        • 3





          @Florin - there is no difference re "stack based" between the two. Static fields are just as much "external state", and will absolutely be shared between callers. With instances, there is a good chance that different threads have different instances (a common pattern). With statics, it is guaranteed that they all share (not including [ThreadStatic]).

          – Marc Gravell
          Apr 20 '09 at 13:03






        • 2





          @MarcGravell with the ThreadLocal approach is there not still the risk of two threads generating the same sequence if appRandom is accessed at the same time by those two threads? Or does some attribute of the thread contribute to the generated sequence?

          – Pero P.
          Aug 9 '12 at 20:38








        • 5





          @Dan if the object is never exposed publicly: you can. The (very theoretical) risk is that some other thread is locking on it in ways you did not expect.

          – Marc Gravell
          Jan 31 '14 at 22:34






        • 2





          @smiron It's very likely you're simply using the random outside of a lock as well. Locking doesn't prevent all access to what you're locking around - it just makes sure that two lock statements on the same instance will not run concurrently. So lock (syncObject) will only help if all random.Next() calls are also within lock (syncObject). If the scenario you describe does happen even with correct lock usage, it also extremely likely happens in a single-threaded scenario (e.g. Random is subtly broken).

          – Luaan
          Apr 21 '15 at 12:17














        • 13





          As a general rule, all static methods should be made thread-safe, since it is hard to guarantee that multiple threads won't call it at the same time. It is not usually necessary to make instance (i.e. non-static) methods thread-safe.

          – Marc Gravell
          Apr 20 '09 at 12:32






        • 3





          @Florin - there is no difference re "stack based" between the two. Static fields are just as much "external state", and will absolutely be shared between callers. With instances, there is a good chance that different threads have different instances (a common pattern). With statics, it is guaranteed that they all share (not including [ThreadStatic]).

          – Marc Gravell
          Apr 20 '09 at 13:03






        • 2





          @MarcGravell with the ThreadLocal approach is there not still the risk of two threads generating the same sequence if appRandom is accessed at the same time by those two threads? Or does some attribute of the thread contribute to the generated sequence?

          – Pero P.
          Aug 9 '12 at 20:38








        • 5





          @Dan if the object is never exposed publicly: you can. The (very theoretical) risk is that some other thread is locking on it in ways you did not expect.

          – Marc Gravell
          Jan 31 '14 at 22:34






        • 2





          @smiron It's very likely you're simply using the random outside of a lock as well. Locking doesn't prevent all access to what you're locking around - it just makes sure that two lock statements on the same instance will not run concurrently. So lock (syncObject) will only help if all random.Next() calls are also within lock (syncObject). If the scenario you describe does happen even with correct lock usage, it also extremely likely happens in a single-threaded scenario (e.g. Random is subtly broken).

          – Luaan
          Apr 21 '15 at 12:17








        13




        13





        As a general rule, all static methods should be made thread-safe, since it is hard to guarantee that multiple threads won't call it at the same time. It is not usually necessary to make instance (i.e. non-static) methods thread-safe.

        – Marc Gravell
        Apr 20 '09 at 12:32





        As a general rule, all static methods should be made thread-safe, since it is hard to guarantee that multiple threads won't call it at the same time. It is not usually necessary to make instance (i.e. non-static) methods thread-safe.

        – Marc Gravell
        Apr 20 '09 at 12:32




        3




        3





        @Florin - there is no difference re "stack based" between the two. Static fields are just as much "external state", and will absolutely be shared between callers. With instances, there is a good chance that different threads have different instances (a common pattern). With statics, it is guaranteed that they all share (not including [ThreadStatic]).

        – Marc Gravell
        Apr 20 '09 at 13:03





        @Florin - there is no difference re "stack based" between the two. Static fields are just as much "external state", and will absolutely be shared between callers. With instances, there is a good chance that different threads have different instances (a common pattern). With statics, it is guaranteed that they all share (not including [ThreadStatic]).

        – Marc Gravell
        Apr 20 '09 at 13:03




        2




        2





        @MarcGravell with the ThreadLocal approach is there not still the risk of two threads generating the same sequence if appRandom is accessed at the same time by those two threads? Or does some attribute of the thread contribute to the generated sequence?

        – Pero P.
        Aug 9 '12 at 20:38







        @MarcGravell with the ThreadLocal approach is there not still the risk of two threads generating the same sequence if appRandom is accessed at the same time by those two threads? Or does some attribute of the thread contribute to the generated sequence?

        – Pero P.
        Aug 9 '12 at 20:38






        5




        5





        @Dan if the object is never exposed publicly: you can. The (very theoretical) risk is that some other thread is locking on it in ways you did not expect.

        – Marc Gravell
        Jan 31 '14 at 22:34





        @Dan if the object is never exposed publicly: you can. The (very theoretical) risk is that some other thread is locking on it in ways you did not expect.

        – Marc Gravell
        Jan 31 '14 at 22:34




        2




        2





        @smiron It's very likely you're simply using the random outside of a lock as well. Locking doesn't prevent all access to what you're locking around - it just makes sure that two lock statements on the same instance will not run concurrently. So lock (syncObject) will only help if all random.Next() calls are also within lock (syncObject). If the scenario you describe does happen even with correct lock usage, it also extremely likely happens in a single-threaded scenario (e.g. Random is subtly broken).

        – Luaan
        Apr 21 '15 at 12:17





        @smiron It's very likely you're simply using the random outside of a lock as well. Locking doesn't prevent all access to what you're locking around - it just makes sure that two lock statements on the same instance will not run concurrently. So lock (syncObject) will only help if all random.Next() calls are also within lock (syncObject). If the scenario you describe does happen even with correct lock usage, it also extremely likely happens in a single-threaded scenario (e.g. Random is subtly broken).

        – Luaan
        Apr 21 '15 at 12:17













        106














        For ease of re-use throughout your application a static class may help.



        public static class StaticRandom
        {
        private static int seed;

        private static ThreadLocal<Random> threadLocal = new ThreadLocal<Random>
        (() => new Random(Interlocked.Increment(ref seed)));

        static StaticRandom()
        {
        seed = Environment.TickCount;
        }

        public static Random Instance { get { return threadLocal.Value; } }
        }


        You can use then use static random instance with code such as



        StaticRandom.Instance.Next(1, 100);





        share|improve this answer






























          106














          For ease of re-use throughout your application a static class may help.



          public static class StaticRandom
          {
          private static int seed;

          private static ThreadLocal<Random> threadLocal = new ThreadLocal<Random>
          (() => new Random(Interlocked.Increment(ref seed)));

          static StaticRandom()
          {
          seed = Environment.TickCount;
          }

          public static Random Instance { get { return threadLocal.Value; } }
          }


          You can use then use static random instance with code such as



          StaticRandom.Instance.Next(1, 100);





          share|improve this answer




























            106












            106








            106







            For ease of re-use throughout your application a static class may help.



            public static class StaticRandom
            {
            private static int seed;

            private static ThreadLocal<Random> threadLocal = new ThreadLocal<Random>
            (() => new Random(Interlocked.Increment(ref seed)));

            static StaticRandom()
            {
            seed = Environment.TickCount;
            }

            public static Random Instance { get { return threadLocal.Value; } }
            }


            You can use then use static random instance with code such as



            StaticRandom.Instance.Next(1, 100);





            share|improve this answer















            For ease of re-use throughout your application a static class may help.



            public static class StaticRandom
            {
            private static int seed;

            private static ThreadLocal<Random> threadLocal = new ThreadLocal<Random>
            (() => new Random(Interlocked.Increment(ref seed)));

            static StaticRandom()
            {
            seed = Environment.TickCount;
            }

            public static Random Instance { get { return threadLocal.Value; } }
            }


            You can use then use static random instance with code such as



            StaticRandom.Instance.Next(1, 100);






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Aug 27 '17 at 22:05

























            answered Jul 13 '12 at 15:25









            PhilPhil

            1,75721325




            1,75721325























                57














                Mark's solution can be quite expensive since it needs to synchronize everytime.



                We can get around the need for synchronization by using the thread-specific storage pattern:




                public class RandomNumber : IRandomNumber
                {
                private static readonly Random Global = new Random();
                [ThreadStatic] private static Random _local;

                public int Next(int max)
                {
                var localBuffer = _local;
                if (localBuffer == null)
                {
                int seed;
                lock(Global) seed = Global.Next();
                localBuffer = new Random(seed);
                _local = localBuffer;
                }
                return localBuffer.Next(max);
                }
                }



                Measure the two implementations and you should see a significant difference.






                share|improve this answer



















                • 11





                  Locks are very cheap when they aren't contested... and even if contested I would expect the "now do something with the number" code to dwarf the cost of the lock in most interesting scenarios.

                  – Marc Gravell
                  Sep 18 '09 at 15:57






                • 4





                  Agreed, this solves the locking problem, but isn't this still a highly complicated solution to a trivial problem: that you need to write ''two'' lines of code to generate a random number instead of one. Is this really worth it to save reading one simple line of code?

                  – EMP
                  Apr 15 '10 at 23:07






                • 4





                  +1 Using an additional global Random instance for getting the seed is a nice idea. Note also that the code can be further simplified using the ThreadLocal<T> class introduced in .NET 4 (as Phil also wrote below).

                  – Groo
                  May 9 '14 at 8:41


















                57














                Mark's solution can be quite expensive since it needs to synchronize everytime.



                We can get around the need for synchronization by using the thread-specific storage pattern:




                public class RandomNumber : IRandomNumber
                {
                private static readonly Random Global = new Random();
                [ThreadStatic] private static Random _local;

                public int Next(int max)
                {
                var localBuffer = _local;
                if (localBuffer == null)
                {
                int seed;
                lock(Global) seed = Global.Next();
                localBuffer = new Random(seed);
                _local = localBuffer;
                }
                return localBuffer.Next(max);
                }
                }



                Measure the two implementations and you should see a significant difference.






                share|improve this answer



















                • 11





                  Locks are very cheap when they aren't contested... and even if contested I would expect the "now do something with the number" code to dwarf the cost of the lock in most interesting scenarios.

                  – Marc Gravell
                  Sep 18 '09 at 15:57






                • 4





                  Agreed, this solves the locking problem, but isn't this still a highly complicated solution to a trivial problem: that you need to write ''two'' lines of code to generate a random number instead of one. Is this really worth it to save reading one simple line of code?

                  – EMP
                  Apr 15 '10 at 23:07






                • 4





                  +1 Using an additional global Random instance for getting the seed is a nice idea. Note also that the code can be further simplified using the ThreadLocal<T> class introduced in .NET 4 (as Phil also wrote below).

                  – Groo
                  May 9 '14 at 8:41
















                57












                57








                57







                Mark's solution can be quite expensive since it needs to synchronize everytime.



                We can get around the need for synchronization by using the thread-specific storage pattern:




                public class RandomNumber : IRandomNumber
                {
                private static readonly Random Global = new Random();
                [ThreadStatic] private static Random _local;

                public int Next(int max)
                {
                var localBuffer = _local;
                if (localBuffer == null)
                {
                int seed;
                lock(Global) seed = Global.Next();
                localBuffer = new Random(seed);
                _local = localBuffer;
                }
                return localBuffer.Next(max);
                }
                }



                Measure the two implementations and you should see a significant difference.






                share|improve this answer













                Mark's solution can be quite expensive since it needs to synchronize everytime.



                We can get around the need for synchronization by using the thread-specific storage pattern:




                public class RandomNumber : IRandomNumber
                {
                private static readonly Random Global = new Random();
                [ThreadStatic] private static Random _local;

                public int Next(int max)
                {
                var localBuffer = _local;
                if (localBuffer == null)
                {
                int seed;
                lock(Global) seed = Global.Next();
                localBuffer = new Random(seed);
                _local = localBuffer;
                }
                return localBuffer.Next(max);
                }
                }



                Measure the two implementations and you should see a significant difference.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Jun 23 '09 at 11:26









                Hans MalherbeHans Malherbe

                2,4501518




                2,4501518








                • 11





                  Locks are very cheap when they aren't contested... and even if contested I would expect the "now do something with the number" code to dwarf the cost of the lock in most interesting scenarios.

                  – Marc Gravell
                  Sep 18 '09 at 15:57






                • 4





                  Agreed, this solves the locking problem, but isn't this still a highly complicated solution to a trivial problem: that you need to write ''two'' lines of code to generate a random number instead of one. Is this really worth it to save reading one simple line of code?

                  – EMP
                  Apr 15 '10 at 23:07






                • 4





                  +1 Using an additional global Random instance for getting the seed is a nice idea. Note also that the code can be further simplified using the ThreadLocal<T> class introduced in .NET 4 (as Phil also wrote below).

                  – Groo
                  May 9 '14 at 8:41
















                • 11





                  Locks are very cheap when they aren't contested... and even if contested I would expect the "now do something with the number" code to dwarf the cost of the lock in most interesting scenarios.

                  – Marc Gravell
                  Sep 18 '09 at 15:57






                • 4





                  Agreed, this solves the locking problem, but isn't this still a highly complicated solution to a trivial problem: that you need to write ''two'' lines of code to generate a random number instead of one. Is this really worth it to save reading one simple line of code?

                  – EMP
                  Apr 15 '10 at 23:07






                • 4





                  +1 Using an additional global Random instance for getting the seed is a nice idea. Note also that the code can be further simplified using the ThreadLocal<T> class introduced in .NET 4 (as Phil also wrote below).

                  – Groo
                  May 9 '14 at 8:41










                11




                11





                Locks are very cheap when they aren't contested... and even if contested I would expect the "now do something with the number" code to dwarf the cost of the lock in most interesting scenarios.

                – Marc Gravell
                Sep 18 '09 at 15:57





                Locks are very cheap when they aren't contested... and even if contested I would expect the "now do something with the number" code to dwarf the cost of the lock in most interesting scenarios.

                – Marc Gravell
                Sep 18 '09 at 15:57




                4




                4





                Agreed, this solves the locking problem, but isn't this still a highly complicated solution to a trivial problem: that you need to write ''two'' lines of code to generate a random number instead of one. Is this really worth it to save reading one simple line of code?

                – EMP
                Apr 15 '10 at 23:07





                Agreed, this solves the locking problem, but isn't this still a highly complicated solution to a trivial problem: that you need to write ''two'' lines of code to generate a random number instead of one. Is this really worth it to save reading one simple line of code?

                – EMP
                Apr 15 '10 at 23:07




                4




                4





                +1 Using an additional global Random instance for getting the seed is a nice idea. Note also that the code can be further simplified using the ThreadLocal<T> class introduced in .NET 4 (as Phil also wrote below).

                – Groo
                May 9 '14 at 8:41







                +1 Using an additional global Random instance for getting the seed is a nice idea. Note also that the code can be further simplified using the ThreadLocal<T> class introduced in .NET 4 (as Phil also wrote below).

                – Groo
                May 9 '14 at 8:41













                35














                My answer from here:



                Just reiterating the right solution:



                namespace mySpace
                {
                public static class Util
                {
                private static rnd = new Random();
                public static int GetRandom()
                {
                return rnd.Next();
                }
                }
                }


                So you can call:



                var i = Util.GetRandom();


                all throughout.



                If you strictly need a true stateless static method to generate random numbers, you can rely on a Guid.



                public static class Util
                {
                public static int GetRandom()
                {
                return Guid.NewGuid().GetHashCode();
                }
                }


                It's going to be a wee bit slower, but can be much more random than Random.Next, at least from my experience.



                But not:



                new Random(Guid.NewGuid().GetHashCode()).Next();


                The unnecessary object creation is going to make it slower especially under a loop.



                And never:



                new Random().Next();


                Not only it's slower (inside a loop), its randomness is... well not really good according to me..






                share|improve this answer





















                • 7





                  I do not agree with the Guid case. The Random class implements a uniform distribution. Which is not the case in Guid. Guid aim is to be unique not uniformly distributed (and its implementation is most of the time based on some hardware/machine property which is the opposite of ... randomness).

                  – Askolein
                  Mar 31 '13 at 13:37






                • 3





                  if you cannot prove the uniformity of Guid generation , then it is wrong to use it as random (and the Hash would be another step away from uniformity). Likewise, collisions aren't an issue: uniformity of collision is. Concerning the Guid generation not being on hardware anymore I'm going to RTFM, my bad (any reference?)

                  – Askolein
                  Mar 31 '13 at 14:18








                • 5





                  There is two understandings of "Random": 1. lack of pattern or 2. lack of pattern following an evolution described by a probability distribution (2 included in 1). Your Guid example is correct in case 1, not in case 2. In opposite: Random class matches case 2 (thus, case 1 too). You can only replace the usage of Random by your Guid+Hash if you are not in case 2. Case 1 is probably enough to answer the Question, and then, your Guid+Hash works fine. But it is not clearly said (ps: this uniform)

                  – Askolein
                  Mar 31 '13 at 17:33






                • 2





                  @Askolein Just for some test data, I run several batches of both Random and Guid.NewGuid().GetHashCode() through Ent (fourmilab.ch/random) and both are similarly random. new Random(Guid.NewGuid().GetHashCode()) works just as well, as does using a synchronized "master" Random to generate seeds for "child" Randoms.. Of course, it does depend on how your system generates Guids - for my system, they are quite random, and on others it may even be crypto-random. So Windows or MS SQL seems fine nowadays. Mono and/or mobile might be different, though.

                  – Luaan
                  Apr 21 '15 at 12:29






                • 2





                  @EdB As I have said in comments previously, while Guid (a large number) is meant to be unique, the GetHashCode of the Guid in .NET is derived from its string representation. The output is quite random for my liking.

                  – nawfal
                  Aug 3 '15 at 17:28
















                35














                My answer from here:



                Just reiterating the right solution:



                namespace mySpace
                {
                public static class Util
                {
                private static rnd = new Random();
                public static int GetRandom()
                {
                return rnd.Next();
                }
                }
                }


                So you can call:



                var i = Util.GetRandom();


                all throughout.



                If you strictly need a true stateless static method to generate random numbers, you can rely on a Guid.



                public static class Util
                {
                public static int GetRandom()
                {
                return Guid.NewGuid().GetHashCode();
                }
                }


                It's going to be a wee bit slower, but can be much more random than Random.Next, at least from my experience.



                But not:



                new Random(Guid.NewGuid().GetHashCode()).Next();


                The unnecessary object creation is going to make it slower especially under a loop.



                And never:



                new Random().Next();


                Not only it's slower (inside a loop), its randomness is... well not really good according to me..






                share|improve this answer





















                • 7





                  I do not agree with the Guid case. The Random class implements a uniform distribution. Which is not the case in Guid. Guid aim is to be unique not uniformly distributed (and its implementation is most of the time based on some hardware/machine property which is the opposite of ... randomness).

                  – Askolein
                  Mar 31 '13 at 13:37






                • 3





                  if you cannot prove the uniformity of Guid generation , then it is wrong to use it as random (and the Hash would be another step away from uniformity). Likewise, collisions aren't an issue: uniformity of collision is. Concerning the Guid generation not being on hardware anymore I'm going to RTFM, my bad (any reference?)

                  – Askolein
                  Mar 31 '13 at 14:18








                • 5





                  There is two understandings of "Random": 1. lack of pattern or 2. lack of pattern following an evolution described by a probability distribution (2 included in 1). Your Guid example is correct in case 1, not in case 2. In opposite: Random class matches case 2 (thus, case 1 too). You can only replace the usage of Random by your Guid+Hash if you are not in case 2. Case 1 is probably enough to answer the Question, and then, your Guid+Hash works fine. But it is not clearly said (ps: this uniform)

                  – Askolein
                  Mar 31 '13 at 17:33






                • 2





                  @Askolein Just for some test data, I run several batches of both Random and Guid.NewGuid().GetHashCode() through Ent (fourmilab.ch/random) and both are similarly random. new Random(Guid.NewGuid().GetHashCode()) works just as well, as does using a synchronized "master" Random to generate seeds for "child" Randoms.. Of course, it does depend on how your system generates Guids - for my system, they are quite random, and on others it may even be crypto-random. So Windows or MS SQL seems fine nowadays. Mono and/or mobile might be different, though.

                  – Luaan
                  Apr 21 '15 at 12:29






                • 2





                  @EdB As I have said in comments previously, while Guid (a large number) is meant to be unique, the GetHashCode of the Guid in .NET is derived from its string representation. The output is quite random for my liking.

                  – nawfal
                  Aug 3 '15 at 17:28














                35












                35








                35







                My answer from here:



                Just reiterating the right solution:



                namespace mySpace
                {
                public static class Util
                {
                private static rnd = new Random();
                public static int GetRandom()
                {
                return rnd.Next();
                }
                }
                }


                So you can call:



                var i = Util.GetRandom();


                all throughout.



                If you strictly need a true stateless static method to generate random numbers, you can rely on a Guid.



                public static class Util
                {
                public static int GetRandom()
                {
                return Guid.NewGuid().GetHashCode();
                }
                }


                It's going to be a wee bit slower, but can be much more random than Random.Next, at least from my experience.



                But not:



                new Random(Guid.NewGuid().GetHashCode()).Next();


                The unnecessary object creation is going to make it slower especially under a loop.



                And never:



                new Random().Next();


                Not only it's slower (inside a loop), its randomness is... well not really good according to me..






                share|improve this answer















                My answer from here:



                Just reiterating the right solution:



                namespace mySpace
                {
                public static class Util
                {
                private static rnd = new Random();
                public static int GetRandom()
                {
                return rnd.Next();
                }
                }
                }


                So you can call:



                var i = Util.GetRandom();


                all throughout.



                If you strictly need a true stateless static method to generate random numbers, you can rely on a Guid.



                public static class Util
                {
                public static int GetRandom()
                {
                return Guid.NewGuid().GetHashCode();
                }
                }


                It's going to be a wee bit slower, but can be much more random than Random.Next, at least from my experience.



                But not:



                new Random(Guid.NewGuid().GetHashCode()).Next();


                The unnecessary object creation is going to make it slower especially under a loop.



                And never:



                new Random().Next();


                Not only it's slower (inside a loop), its randomness is... well not really good according to me..







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited May 23 '17 at 11:55









                Community

                11




                11










                answered Mar 31 '13 at 12:34









                nawfalnawfal

                43.4k36256299




                43.4k36256299








                • 7





                  I do not agree with the Guid case. The Random class implements a uniform distribution. Which is not the case in Guid. Guid aim is to be unique not uniformly distributed (and its implementation is most of the time based on some hardware/machine property which is the opposite of ... randomness).

                  – Askolein
                  Mar 31 '13 at 13:37






                • 3





                  if you cannot prove the uniformity of Guid generation , then it is wrong to use it as random (and the Hash would be another step away from uniformity). Likewise, collisions aren't an issue: uniformity of collision is. Concerning the Guid generation not being on hardware anymore I'm going to RTFM, my bad (any reference?)

                  – Askolein
                  Mar 31 '13 at 14:18








                • 5





                  There is two understandings of "Random": 1. lack of pattern or 2. lack of pattern following an evolution described by a probability distribution (2 included in 1). Your Guid example is correct in case 1, not in case 2. In opposite: Random class matches case 2 (thus, case 1 too). You can only replace the usage of Random by your Guid+Hash if you are not in case 2. Case 1 is probably enough to answer the Question, and then, your Guid+Hash works fine. But it is not clearly said (ps: this uniform)

                  – Askolein
                  Mar 31 '13 at 17:33






                • 2





                  @Askolein Just for some test data, I run several batches of both Random and Guid.NewGuid().GetHashCode() through Ent (fourmilab.ch/random) and both are similarly random. new Random(Guid.NewGuid().GetHashCode()) works just as well, as does using a synchronized "master" Random to generate seeds for "child" Randoms.. Of course, it does depend on how your system generates Guids - for my system, they are quite random, and on others it may even be crypto-random. So Windows or MS SQL seems fine nowadays. Mono and/or mobile might be different, though.

                  – Luaan
                  Apr 21 '15 at 12:29






                • 2





                  @EdB As I have said in comments previously, while Guid (a large number) is meant to be unique, the GetHashCode of the Guid in .NET is derived from its string representation. The output is quite random for my liking.

                  – nawfal
                  Aug 3 '15 at 17:28














                • 7





                  I do not agree with the Guid case. The Random class implements a uniform distribution. Which is not the case in Guid. Guid aim is to be unique not uniformly distributed (and its implementation is most of the time based on some hardware/machine property which is the opposite of ... randomness).

                  – Askolein
                  Mar 31 '13 at 13:37






                • 3





                  if you cannot prove the uniformity of Guid generation , then it is wrong to use it as random (and the Hash would be another step away from uniformity). Likewise, collisions aren't an issue: uniformity of collision is. Concerning the Guid generation not being on hardware anymore I'm going to RTFM, my bad (any reference?)

                  – Askolein
                  Mar 31 '13 at 14:18








                • 5





                  There is two understandings of "Random": 1. lack of pattern or 2. lack of pattern following an evolution described by a probability distribution (2 included in 1). Your Guid example is correct in case 1, not in case 2. In opposite: Random class matches case 2 (thus, case 1 too). You can only replace the usage of Random by your Guid+Hash if you are not in case 2. Case 1 is probably enough to answer the Question, and then, your Guid+Hash works fine. But it is not clearly said (ps: this uniform)

                  – Askolein
                  Mar 31 '13 at 17:33






                • 2





                  @Askolein Just for some test data, I run several batches of both Random and Guid.NewGuid().GetHashCode() through Ent (fourmilab.ch/random) and both are similarly random. new Random(Guid.NewGuid().GetHashCode()) works just as well, as does using a synchronized "master" Random to generate seeds for "child" Randoms.. Of course, it does depend on how your system generates Guids - for my system, they are quite random, and on others it may even be crypto-random. So Windows or MS SQL seems fine nowadays. Mono and/or mobile might be different, though.

                  – Luaan
                  Apr 21 '15 at 12:29






                • 2





                  @EdB As I have said in comments previously, while Guid (a large number) is meant to be unique, the GetHashCode of the Guid in .NET is derived from its string representation. The output is quite random for my liking.

                  – nawfal
                  Aug 3 '15 at 17:28








                7




                7





                I do not agree with the Guid case. The Random class implements a uniform distribution. Which is not the case in Guid. Guid aim is to be unique not uniformly distributed (and its implementation is most of the time based on some hardware/machine property which is the opposite of ... randomness).

                – Askolein
                Mar 31 '13 at 13:37





                I do not agree with the Guid case. The Random class implements a uniform distribution. Which is not the case in Guid. Guid aim is to be unique not uniformly distributed (and its implementation is most of the time based on some hardware/machine property which is the opposite of ... randomness).

                – Askolein
                Mar 31 '13 at 13:37




                3




                3





                if you cannot prove the uniformity of Guid generation , then it is wrong to use it as random (and the Hash would be another step away from uniformity). Likewise, collisions aren't an issue: uniformity of collision is. Concerning the Guid generation not being on hardware anymore I'm going to RTFM, my bad (any reference?)

                – Askolein
                Mar 31 '13 at 14:18







                if you cannot prove the uniformity of Guid generation , then it is wrong to use it as random (and the Hash would be another step away from uniformity). Likewise, collisions aren't an issue: uniformity of collision is. Concerning the Guid generation not being on hardware anymore I'm going to RTFM, my bad (any reference?)

                – Askolein
                Mar 31 '13 at 14:18






                5




                5





                There is two understandings of "Random": 1. lack of pattern or 2. lack of pattern following an evolution described by a probability distribution (2 included in 1). Your Guid example is correct in case 1, not in case 2. In opposite: Random class matches case 2 (thus, case 1 too). You can only replace the usage of Random by your Guid+Hash if you are not in case 2. Case 1 is probably enough to answer the Question, and then, your Guid+Hash works fine. But it is not clearly said (ps: this uniform)

                – Askolein
                Mar 31 '13 at 17:33





                There is two understandings of "Random": 1. lack of pattern or 2. lack of pattern following an evolution described by a probability distribution (2 included in 1). Your Guid example is correct in case 1, not in case 2. In opposite: Random class matches case 2 (thus, case 1 too). You can only replace the usage of Random by your Guid+Hash if you are not in case 2. Case 1 is probably enough to answer the Question, and then, your Guid+Hash works fine. But it is not clearly said (ps: this uniform)

                – Askolein
                Mar 31 '13 at 17:33




                2




                2





                @Askolein Just for some test data, I run several batches of both Random and Guid.NewGuid().GetHashCode() through Ent (fourmilab.ch/random) and both are similarly random. new Random(Guid.NewGuid().GetHashCode()) works just as well, as does using a synchronized "master" Random to generate seeds for "child" Randoms.. Of course, it does depend on how your system generates Guids - for my system, they are quite random, and on others it may even be crypto-random. So Windows or MS SQL seems fine nowadays. Mono and/or mobile might be different, though.

                – Luaan
                Apr 21 '15 at 12:29





                @Askolein Just for some test data, I run several batches of both Random and Guid.NewGuid().GetHashCode() through Ent (fourmilab.ch/random) and both are similarly random. new Random(Guid.NewGuid().GetHashCode()) works just as well, as does using a synchronized "master" Random to generate seeds for "child" Randoms.. Of course, it does depend on how your system generates Guids - for my system, they are quite random, and on others it may even be crypto-random. So Windows or MS SQL seems fine nowadays. Mono and/or mobile might be different, though.

                – Luaan
                Apr 21 '15 at 12:29




                2




                2





                @EdB As I have said in comments previously, while Guid (a large number) is meant to be unique, the GetHashCode of the Guid in .NET is derived from its string representation. The output is quite random for my liking.

                – nawfal
                Aug 3 '15 at 17:28





                @EdB As I have said in comments previously, while Guid (a large number) is meant to be unique, the GetHashCode of the Guid in .NET is derived from its string representation. The output is quite random for my liking.

                – nawfal
                Aug 3 '15 at 17:28











                23














                I would rather use the following class to generate random numbers:



                byte random;
                System.Security.Cryptography.RNGCryptoServiceProvider prov = new System.Security.Cryptography.RNGCryptoServiceProvider();
                prov.GetBytes(random);





                share|improve this answer





















                • 30





                  I'm not one of the down-voters, but note that standard PNRG do serve a genuine need - i.e. to be able to repeatably reproduce a sequence from a known seed. Sometimes the sheer cost of a true cryptographic RNG is too much. And sometimes a crypto RNG is necessary. Horses for courses, so to speak.

                  – Marc Gravell
                  Apr 20 '09 at 12:35






                • 4





                  According to the documentation this class is thread-safe, so that's something in it's favour.

                  – Rob Church
                  Apr 26 '13 at 13:51











                • What is the probability two random strings to be one and the same using that? If the string is just 3 characters I guess this will happen with high probability but what if is 255 characters length is it possible to have the same random string or is guaranteed that this can't happen from the algorithm?

                  – Lyubomir Velchev
                  Jul 12 '16 at 13:03
















                23














                I would rather use the following class to generate random numbers:



                byte random;
                System.Security.Cryptography.RNGCryptoServiceProvider prov = new System.Security.Cryptography.RNGCryptoServiceProvider();
                prov.GetBytes(random);





                share|improve this answer





















                • 30





                  I'm not one of the down-voters, but note that standard PNRG do serve a genuine need - i.e. to be able to repeatably reproduce a sequence from a known seed. Sometimes the sheer cost of a true cryptographic RNG is too much. And sometimes a crypto RNG is necessary. Horses for courses, so to speak.

                  – Marc Gravell
                  Apr 20 '09 at 12:35






                • 4





                  According to the documentation this class is thread-safe, so that's something in it's favour.

                  – Rob Church
                  Apr 26 '13 at 13:51











                • What is the probability two random strings to be one and the same using that? If the string is just 3 characters I guess this will happen with high probability but what if is 255 characters length is it possible to have the same random string or is guaranteed that this can't happen from the algorithm?

                  – Lyubomir Velchev
                  Jul 12 '16 at 13:03














                23












                23








                23







                I would rather use the following class to generate random numbers:



                byte random;
                System.Security.Cryptography.RNGCryptoServiceProvider prov = new System.Security.Cryptography.RNGCryptoServiceProvider();
                prov.GetBytes(random);





                share|improve this answer















                I would rather use the following class to generate random numbers:



                byte random;
                System.Security.Cryptography.RNGCryptoServiceProvider prov = new System.Security.Cryptography.RNGCryptoServiceProvider();
                prov.GetBytes(random);






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Oct 22 '12 at 17:43









                Picrofo Software

                4,74031735




                4,74031735










                answered Apr 20 '09 at 12:25









                fARcRYfARcRY

                1,56751838




                1,56751838








                • 30





                  I'm not one of the down-voters, but note that standard PNRG do serve a genuine need - i.e. to be able to repeatably reproduce a sequence from a known seed. Sometimes the sheer cost of a true cryptographic RNG is too much. And sometimes a crypto RNG is necessary. Horses for courses, so to speak.

                  – Marc Gravell
                  Apr 20 '09 at 12:35






                • 4





                  According to the documentation this class is thread-safe, so that's something in it's favour.

                  – Rob Church
                  Apr 26 '13 at 13:51











                • What is the probability two random strings to be one and the same using that? If the string is just 3 characters I guess this will happen with high probability but what if is 255 characters length is it possible to have the same random string or is guaranteed that this can't happen from the algorithm?

                  – Lyubomir Velchev
                  Jul 12 '16 at 13:03














                • 30





                  I'm not one of the down-voters, but note that standard PNRG do serve a genuine need - i.e. to be able to repeatably reproduce a sequence from a known seed. Sometimes the sheer cost of a true cryptographic RNG is too much. And sometimes a crypto RNG is necessary. Horses for courses, so to speak.

                  – Marc Gravell
                  Apr 20 '09 at 12:35






                • 4





                  According to the documentation this class is thread-safe, so that's something in it's favour.

                  – Rob Church
                  Apr 26 '13 at 13:51











                • What is the probability two random strings to be one and the same using that? If the string is just 3 characters I guess this will happen with high probability but what if is 255 characters length is it possible to have the same random string or is guaranteed that this can't happen from the algorithm?

                  – Lyubomir Velchev
                  Jul 12 '16 at 13:03








                30




                30





                I'm not one of the down-voters, but note that standard PNRG do serve a genuine need - i.e. to be able to repeatably reproduce a sequence from a known seed. Sometimes the sheer cost of a true cryptographic RNG is too much. And sometimes a crypto RNG is necessary. Horses for courses, so to speak.

                – Marc Gravell
                Apr 20 '09 at 12:35





                I'm not one of the down-voters, but note that standard PNRG do serve a genuine need - i.e. to be able to repeatably reproduce a sequence from a known seed. Sometimes the sheer cost of a true cryptographic RNG is too much. And sometimes a crypto RNG is necessary. Horses for courses, so to speak.

                – Marc Gravell
                Apr 20 '09 at 12:35




                4




                4





                According to the documentation this class is thread-safe, so that's something in it's favour.

                – Rob Church
                Apr 26 '13 at 13:51





                According to the documentation this class is thread-safe, so that's something in it's favour.

                – Rob Church
                Apr 26 '13 at 13:51













                What is the probability two random strings to be one and the same using that? If the string is just 3 characters I guess this will happen with high probability but what if is 255 characters length is it possible to have the same random string or is guaranteed that this can't happen from the algorithm?

                – Lyubomir Velchev
                Jul 12 '16 at 13:03





                What is the probability two random strings to be one and the same using that? If the string is just 3 characters I guess this will happen with high probability but what if is 255 characters length is it possible to have the same random string or is guaranteed that this can't happen from the algorithm?

                – Lyubomir Velchev
                Jul 12 '16 at 13:03











                13














                1) As Marc Gravell said, try to use ONE random-generator. It's always cool to add this to the constructor: System.Environment.TickCount.



                2) One tip. Let's say you want to create 100 objects and suppose each of them should have its-own random-generator (handy if you calculate LOADS of random numbers in a very short period of time). If you would do this in a loop (generation of 100 objects), you could do this like that (to assure fully-randomness):



                int inMyRandSeed;

                for(int i=0;i<100;i++)
                {
                inMyRandSeed = System.Environment.TickCount + i;
                .
                .
                .
                myNewObject = new MyNewObject(inMyRandSeed);
                .
                .
                .
                }

                // Usage: Random m_rndGen = new Random(inMyRandSeed);


                Cheers.






                share|improve this answer





















                • 3





                  I would move System.Environment.TickCount out of the loop. If it ticks over while you are iterating then you will have two items initialized to the same seed. Another option would be to combine the tickcount an i differently (e.g. System.Environment.TickCount<<8 + i)

                  – Dolphin
                  Jun 25 '09 at 19:03











                • If I understand correctly: do you mean, it could happen, that "System.Environment.TickCount + i" could result the SAME value?

                  – sabiland
                  Jun 26 '09 at 13:18











                • EDIT: Of course, no need to have TickCount inside the loop. My bad :).

                  – sabiland
                  Jun 26 '09 at 13:19






                • 2





                  The default Random() constructor calls Random(Environment.TickCount) anyway

                  – Alsty
                  Feb 16 '17 at 16:29
















                13














                1) As Marc Gravell said, try to use ONE random-generator. It's always cool to add this to the constructor: System.Environment.TickCount.



                2) One tip. Let's say you want to create 100 objects and suppose each of them should have its-own random-generator (handy if you calculate LOADS of random numbers in a very short period of time). If you would do this in a loop (generation of 100 objects), you could do this like that (to assure fully-randomness):



                int inMyRandSeed;

                for(int i=0;i<100;i++)
                {
                inMyRandSeed = System.Environment.TickCount + i;
                .
                .
                .
                myNewObject = new MyNewObject(inMyRandSeed);
                .
                .
                .
                }

                // Usage: Random m_rndGen = new Random(inMyRandSeed);


                Cheers.






                share|improve this answer





















                • 3





                  I would move System.Environment.TickCount out of the loop. If it ticks over while you are iterating then you will have two items initialized to the same seed. Another option would be to combine the tickcount an i differently (e.g. System.Environment.TickCount<<8 + i)

                  – Dolphin
                  Jun 25 '09 at 19:03











                • If I understand correctly: do you mean, it could happen, that "System.Environment.TickCount + i" could result the SAME value?

                  – sabiland
                  Jun 26 '09 at 13:18











                • EDIT: Of course, no need to have TickCount inside the loop. My bad :).

                  – sabiland
                  Jun 26 '09 at 13:19






                • 2





                  The default Random() constructor calls Random(Environment.TickCount) anyway

                  – Alsty
                  Feb 16 '17 at 16:29














                13












                13








                13







                1) As Marc Gravell said, try to use ONE random-generator. It's always cool to add this to the constructor: System.Environment.TickCount.



                2) One tip. Let's say you want to create 100 objects and suppose each of them should have its-own random-generator (handy if you calculate LOADS of random numbers in a very short period of time). If you would do this in a loop (generation of 100 objects), you could do this like that (to assure fully-randomness):



                int inMyRandSeed;

                for(int i=0;i<100;i++)
                {
                inMyRandSeed = System.Environment.TickCount + i;
                .
                .
                .
                myNewObject = new MyNewObject(inMyRandSeed);
                .
                .
                .
                }

                // Usage: Random m_rndGen = new Random(inMyRandSeed);


                Cheers.






                share|improve this answer















                1) As Marc Gravell said, try to use ONE random-generator. It's always cool to add this to the constructor: System.Environment.TickCount.



                2) One tip. Let's say you want to create 100 objects and suppose each of them should have its-own random-generator (handy if you calculate LOADS of random numbers in a very short period of time). If you would do this in a loop (generation of 100 objects), you could do this like that (to assure fully-randomness):



                int inMyRandSeed;

                for(int i=0;i<100;i++)
                {
                inMyRandSeed = System.Environment.TickCount + i;
                .
                .
                .
                myNewObject = new MyNewObject(inMyRandSeed);
                .
                .
                .
                }

                // Usage: Random m_rndGen = new Random(inMyRandSeed);


                Cheers.







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Jun 25 '09 at 17:24


























                community wiki





                3 revs, 3 users 88%
                sabiland










                • 3





                  I would move System.Environment.TickCount out of the loop. If it ticks over while you are iterating then you will have two items initialized to the same seed. Another option would be to combine the tickcount an i differently (e.g. System.Environment.TickCount<<8 + i)

                  – Dolphin
                  Jun 25 '09 at 19:03











                • If I understand correctly: do you mean, it could happen, that "System.Environment.TickCount + i" could result the SAME value?

                  – sabiland
                  Jun 26 '09 at 13:18











                • EDIT: Of course, no need to have TickCount inside the loop. My bad :).

                  – sabiland
                  Jun 26 '09 at 13:19






                • 2





                  The default Random() constructor calls Random(Environment.TickCount) anyway

                  – Alsty
                  Feb 16 '17 at 16:29














                • 3





                  I would move System.Environment.TickCount out of the loop. If it ticks over while you are iterating then you will have two items initialized to the same seed. Another option would be to combine the tickcount an i differently (e.g. System.Environment.TickCount<<8 + i)

                  – Dolphin
                  Jun 25 '09 at 19:03











                • If I understand correctly: do you mean, it could happen, that "System.Environment.TickCount + i" could result the SAME value?

                  – sabiland
                  Jun 26 '09 at 13:18











                • EDIT: Of course, no need to have TickCount inside the loop. My bad :).

                  – sabiland
                  Jun 26 '09 at 13:19






                • 2





                  The default Random() constructor calls Random(Environment.TickCount) anyway

                  – Alsty
                  Feb 16 '17 at 16:29








                3




                3





                I would move System.Environment.TickCount out of the loop. If it ticks over while you are iterating then you will have two items initialized to the same seed. Another option would be to combine the tickcount an i differently (e.g. System.Environment.TickCount<<8 + i)

                – Dolphin
                Jun 25 '09 at 19:03





                I would move System.Environment.TickCount out of the loop. If it ticks over while you are iterating then you will have two items initialized to the same seed. Another option would be to combine the tickcount an i differently (e.g. System.Environment.TickCount<<8 + i)

                – Dolphin
                Jun 25 '09 at 19:03













                If I understand correctly: do you mean, it could happen, that "System.Environment.TickCount + i" could result the SAME value?

                – sabiland
                Jun 26 '09 at 13:18





                If I understand correctly: do you mean, it could happen, that "System.Environment.TickCount + i" could result the SAME value?

                – sabiland
                Jun 26 '09 at 13:18













                EDIT: Of course, no need to have TickCount inside the loop. My bad :).

                – sabiland
                Jun 26 '09 at 13:19





                EDIT: Of course, no need to have TickCount inside the loop. My bad :).

                – sabiland
                Jun 26 '09 at 13:19




                2




                2





                The default Random() constructor calls Random(Environment.TickCount) anyway

                – Alsty
                Feb 16 '17 at 16:29





                The default Random() constructor calls Random(Environment.TickCount) anyway

                – Alsty
                Feb 16 '17 at 16:29











                2














                Every time you execute



                Random random = new Random (15);


                It does not matter if you execute it millions of times, you will always use the same seed.



                If you use



                Random random = new Random ();


                You get different random number sequence, if a hacker guesses the seed and your algorithm is related to the security of your system - your algorithm is broken. I you execute mult. In this constructor the seed is specified by the system clock and if several instances are created in a very short period of time (milliseconds) it is possible that they may have the same seed.



                If you need safe random numbers you must use the class




                System.Security.Cryptography.RNGCryptoServiceProvider




                public static int Next(int min, int max)
                {
                if(min >= max)
                {
                throw new ArgumentException("Min value is greater or equals than Max value.");
                }
                byte intBytes = new byte[4];
                using(RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
                {
                rng.GetNonZeroBytes(intBytes);
                }
                return min + Math.Abs(BitConverter.ToInt32(intBytes, 0)) % (max - min + 1);
                }


                Usage:



                int randomNumber = Next(1,100);





                share|improve this answer


























                • It does not matter if you execute it millions of times, you will always use the same seed. That's not true unless you specify the seed yourself.

                  – LarsTech
                  Oct 19 '18 at 17:47











                • Fixed up. Thanks Exactly as you say LarsTech, if the same seed is always specified, the same sequence of random numbers will always be generated. In my answer I refer to the constructor with parameters if you always use the same seed. The Random class generates only pseudo random numbers. If someone finds out what seed you have used in your algorithm, it can compromise the security or randomness of your algorithm. With the RNGCryptoServiceProvider class, you can safely have random numbers. I already corrected, thank you very much for the correction.

                  – Joma
                  Oct 19 '18 at 21:03
















                2














                Every time you execute



                Random random = new Random (15);


                It does not matter if you execute it millions of times, you will always use the same seed.



                If you use



                Random random = new Random ();


                You get different random number sequence, if a hacker guesses the seed and your algorithm is related to the security of your system - your algorithm is broken. I you execute mult. In this constructor the seed is specified by the system clock and if several instances are created in a very short period of time (milliseconds) it is possible that they may have the same seed.



                If you need safe random numbers you must use the class




                System.Security.Cryptography.RNGCryptoServiceProvider




                public static int Next(int min, int max)
                {
                if(min >= max)
                {
                throw new ArgumentException("Min value is greater or equals than Max value.");
                }
                byte intBytes = new byte[4];
                using(RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
                {
                rng.GetNonZeroBytes(intBytes);
                }
                return min + Math.Abs(BitConverter.ToInt32(intBytes, 0)) % (max - min + 1);
                }


                Usage:



                int randomNumber = Next(1,100);





                share|improve this answer


























                • It does not matter if you execute it millions of times, you will always use the same seed. That's not true unless you specify the seed yourself.

                  – LarsTech
                  Oct 19 '18 at 17:47











                • Fixed up. Thanks Exactly as you say LarsTech, if the same seed is always specified, the same sequence of random numbers will always be generated. In my answer I refer to the constructor with parameters if you always use the same seed. The Random class generates only pseudo random numbers. If someone finds out what seed you have used in your algorithm, it can compromise the security or randomness of your algorithm. With the RNGCryptoServiceProvider class, you can safely have random numbers. I already corrected, thank you very much for the correction.

                  – Joma
                  Oct 19 '18 at 21:03














                2












                2








                2







                Every time you execute



                Random random = new Random (15);


                It does not matter if you execute it millions of times, you will always use the same seed.



                If you use



                Random random = new Random ();


                You get different random number sequence, if a hacker guesses the seed and your algorithm is related to the security of your system - your algorithm is broken. I you execute mult. In this constructor the seed is specified by the system clock and if several instances are created in a very short period of time (milliseconds) it is possible that they may have the same seed.



                If you need safe random numbers you must use the class




                System.Security.Cryptography.RNGCryptoServiceProvider




                public static int Next(int min, int max)
                {
                if(min >= max)
                {
                throw new ArgumentException("Min value is greater or equals than Max value.");
                }
                byte intBytes = new byte[4];
                using(RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
                {
                rng.GetNonZeroBytes(intBytes);
                }
                return min + Math.Abs(BitConverter.ToInt32(intBytes, 0)) % (max - min + 1);
                }


                Usage:



                int randomNumber = Next(1,100);





                share|improve this answer















                Every time you execute



                Random random = new Random (15);


                It does not matter if you execute it millions of times, you will always use the same seed.



                If you use



                Random random = new Random ();


                You get different random number sequence, if a hacker guesses the seed and your algorithm is related to the security of your system - your algorithm is broken. I you execute mult. In this constructor the seed is specified by the system clock and if several instances are created in a very short period of time (milliseconds) it is possible that they may have the same seed.



                If you need safe random numbers you must use the class




                System.Security.Cryptography.RNGCryptoServiceProvider




                public static int Next(int min, int max)
                {
                if(min >= max)
                {
                throw new ArgumentException("Min value is greater or equals than Max value.");
                }
                byte intBytes = new byte[4];
                using(RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
                {
                rng.GetNonZeroBytes(intBytes);
                }
                return min + Math.Abs(BitConverter.ToInt32(intBytes, 0)) % (max - min + 1);
                }


                Usage:



                int randomNumber = Next(1,100);






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Oct 19 '18 at 21:17

























                answered Oct 19 '18 at 16:06









                JomaJoma

                440811




                440811













                • It does not matter if you execute it millions of times, you will always use the same seed. That's not true unless you specify the seed yourself.

                  – LarsTech
                  Oct 19 '18 at 17:47











                • Fixed up. Thanks Exactly as you say LarsTech, if the same seed is always specified, the same sequence of random numbers will always be generated. In my answer I refer to the constructor with parameters if you always use the same seed. The Random class generates only pseudo random numbers. If someone finds out what seed you have used in your algorithm, it can compromise the security or randomness of your algorithm. With the RNGCryptoServiceProvider class, you can safely have random numbers. I already corrected, thank you very much for the correction.

                  – Joma
                  Oct 19 '18 at 21:03



















                • It does not matter if you execute it millions of times, you will always use the same seed. That's not true unless you specify the seed yourself.

                  – LarsTech
                  Oct 19 '18 at 17:47











                • Fixed up. Thanks Exactly as you say LarsTech, if the same seed is always specified, the same sequence of random numbers will always be generated. In my answer I refer to the constructor with parameters if you always use the same seed. The Random class generates only pseudo random numbers. If someone finds out what seed you have used in your algorithm, it can compromise the security or randomness of your algorithm. With the RNGCryptoServiceProvider class, you can safely have random numbers. I already corrected, thank you very much for the correction.

                  – Joma
                  Oct 19 '18 at 21:03

















                It does not matter if you execute it millions of times, you will always use the same seed. That's not true unless you specify the seed yourself.

                – LarsTech
                Oct 19 '18 at 17:47





                It does not matter if you execute it millions of times, you will always use the same seed. That's not true unless you specify the seed yourself.

                – LarsTech
                Oct 19 '18 at 17:47













                Fixed up. Thanks Exactly as you say LarsTech, if the same seed is always specified, the same sequence of random numbers will always be generated. In my answer I refer to the constructor with parameters if you always use the same seed. The Random class generates only pseudo random numbers. If someone finds out what seed you have used in your algorithm, it can compromise the security or randomness of your algorithm. With the RNGCryptoServiceProvider class, you can safely have random numbers. I already corrected, thank you very much for the correction.

                – Joma
                Oct 19 '18 at 21:03





                Fixed up. Thanks Exactly as you say LarsTech, if the same seed is always specified, the same sequence of random numbers will always be generated. In my answer I refer to the constructor with parameters if you always use the same seed. The Random class generates only pseudo random numbers. If someone finds out what seed you have used in your algorithm, it can compromise the security or randomness of your algorithm. With the RNGCryptoServiceProvider class, you can safely have random numbers. I already corrected, thank you very much for the correction.

                – Joma
                Oct 19 '18 at 21:03











                2














                just declare the Random class variable like this:



                    Random r = new Random();
                // ... Get three random numbers.
                // Here you'll get numbers from 5 to 9
                Console.WriteLine(r.Next(5, 10));


                if you want to get different random number each time from your list then use



                r.Next(StartPoint,EndPoint) //Here end point will not be included


                Each time by declaring Random r = new Random() once.






                share|improve this answer






























                  2














                  just declare the Random class variable like this:



                      Random r = new Random();
                  // ... Get three random numbers.
                  // Here you'll get numbers from 5 to 9
                  Console.WriteLine(r.Next(5, 10));


                  if you want to get different random number each time from your list then use



                  r.Next(StartPoint,EndPoint) //Here end point will not be included


                  Each time by declaring Random r = new Random() once.






                  share|improve this answer




























                    2












                    2








                    2







                    just declare the Random class variable like this:



                        Random r = new Random();
                    // ... Get three random numbers.
                    // Here you'll get numbers from 5 to 9
                    Console.WriteLine(r.Next(5, 10));


                    if you want to get different random number each time from your list then use



                    r.Next(StartPoint,EndPoint) //Here end point will not be included


                    Each time by declaring Random r = new Random() once.






                    share|improve this answer















                    just declare the Random class variable like this:



                        Random r = new Random();
                    // ... Get three random numbers.
                    // Here you'll get numbers from 5 to 9
                    Console.WriteLine(r.Next(5, 10));


                    if you want to get different random number each time from your list then use



                    r.Next(StartPoint,EndPoint) //Here end point will not be included


                    Each time by declaring Random r = new Random() once.







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Nov 3 '18 at 8:35

























                    answered Oct 11 '18 at 11:57









                    AbdulAbdul

                    263110




                    263110























                        1














                        There are a lot of solutions, here one: if you want only number erase the letters and the method receives a random and the result length.



                        public String GenerateRandom(Random oRandom, int iLongitudPin)
                        {
                        String sCharacters = "123456789ABCDEFGHIJKLMNPQRSTUVWXYZ123456789";
                        int iLength = sCharacters.Length;
                        char cCharacter;
                        int iLongitudNuevaCadena = iLongitudPin;
                        String sRandomResult = "";
                        for (int i = 0; i < iLongitudNuevaCadena; i++)
                        {
                        cCharacter = sCharacters[oRandom.Next(iLength)];
                        sRandomResult += cCharacter.ToString();
                        }
                        return (sRandomResult);
                        }





                        share|improve this answer






























                          1














                          There are a lot of solutions, here one: if you want only number erase the letters and the method receives a random and the result length.



                          public String GenerateRandom(Random oRandom, int iLongitudPin)
                          {
                          String sCharacters = "123456789ABCDEFGHIJKLMNPQRSTUVWXYZ123456789";
                          int iLength = sCharacters.Length;
                          char cCharacter;
                          int iLongitudNuevaCadena = iLongitudPin;
                          String sRandomResult = "";
                          for (int i = 0; i < iLongitudNuevaCadena; i++)
                          {
                          cCharacter = sCharacters[oRandom.Next(iLength)];
                          sRandomResult += cCharacter.ToString();
                          }
                          return (sRandomResult);
                          }





                          share|improve this answer




























                            1












                            1








                            1







                            There are a lot of solutions, here one: if you want only number erase the letters and the method receives a random and the result length.



                            public String GenerateRandom(Random oRandom, int iLongitudPin)
                            {
                            String sCharacters = "123456789ABCDEFGHIJKLMNPQRSTUVWXYZ123456789";
                            int iLength = sCharacters.Length;
                            char cCharacter;
                            int iLongitudNuevaCadena = iLongitudPin;
                            String sRandomResult = "";
                            for (int i = 0; i < iLongitudNuevaCadena; i++)
                            {
                            cCharacter = sCharacters[oRandom.Next(iLength)];
                            sRandomResult += cCharacter.ToString();
                            }
                            return (sRandomResult);
                            }





                            share|improve this answer















                            There are a lot of solutions, here one: if you want only number erase the letters and the method receives a random and the result length.



                            public String GenerateRandom(Random oRandom, int iLongitudPin)
                            {
                            String sCharacters = "123456789ABCDEFGHIJKLMNPQRSTUVWXYZ123456789";
                            int iLength = sCharacters.Length;
                            char cCharacter;
                            int iLongitudNuevaCadena = iLongitudPin;
                            String sRandomResult = "";
                            for (int i = 0; i < iLongitudNuevaCadena; i++)
                            {
                            cCharacter = sCharacters[oRandom.Next(iLength)];
                            sRandomResult += cCharacter.ToString();
                            }
                            return (sRandomResult);
                            }






                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            answered Jun 4 '14 at 5:13


























                            community wiki





                            Marztres


















                                protected by Community Aug 8 '14 at 13:28



                                Thank you for your interest in this question.
                                Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



                                Would you like to answer one of these unanswered questions instead?



                                Popular posts from this blog

                                Florida Star v. B. J. F.

                                Danny Elfman

                                Lugert, Oklahoma