Tuesday, June 25, 2013

C# - Generate random number

Sometimes we need to generate a random number in our application for various purpose (such as, to use it as a part of unique key, etc).

There is a quick way in C#, that can generate a random number. Here, you can also specify the range within which the random number should be generated.

int generatedRandomNumber = new Random(System.DateTime.Now.Millisecond).Next(int.MinValue, int.MaxValue);

This will generate a random number within the range of -2147483648 and 2,147,483,647. But you can narrow down your range to only positive values or some explicit range by changing the parameters in Next function above.

Hope it does help!
 

2 comments:

  1. This technique is flawed. This way you easily get same number, if you query multiple times, even in the same request, with very high probability. You get 1000 different 'random' numbers in total this way.

    ReplyDelete
  2. yes, I agree. This will work in most cases where you need random numbers, but yes, for unique numbers this is definitely not appropriate.

    thanks for highlighting

    ReplyDelete

Thanks for visiting my blog.
However, if this helped you in any way, please take a moment to write a comment.

Thanks
Nirman