2377

How do I generate a random integer in C#?

ADJenks
  • 2,973
  • 27
  • 38
Rella
  • 65,003
  • 109
  • 363
  • 636
  • 2
    See [this answer](https://stackoverflow.com/a/70413499/) for the current (and easiest) cryptographically secure solution – Mafii Jul 12 '22 at 08:10
  • [Random.Shared](https://stackoverflow.com/a/75672033/3994927) is the current way to go on the server side. Cryptographical security is needed in a use case where a single user can infer the inner state of the generator from observing sequences of generated numbers, and also knowing the relative position of the generated numbers whose values they are trying to predict. – Matilda Smeds Apr 25 '23 at 11:01

33 Answers33

3010

The Random class is used to create random numbers. (Pseudo-random that is of course.).

Example:

Random rnd = new Random();
int month  = rnd.Next(1, 13);  // creates a number between 1 and 12
int dice   = rnd.Next(1, 7);   // creates a number between 1 and 6
int card   = rnd.Next(52);     // creates a number between 0 and 51

If you are going to create more than one random number, you should keep the Random instance and reuse it. If you create new instances too close in time, they will produce the same series of random numbers as the random generator is seeded from the system clock.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • Comments are not for extended discussion; this conversation has been [moved to chat](http://chat.stackoverflow.com/rooms/131667/discussion-on-answer-by-guffa-how-do-i-generate-a-random-int-number-in-c). – deceze Dec 28 '16 at 08:45
  • 11
    In order to reuse it, you can declare `rnd` as `static` and/or set it just once when initializing the code. – Junior Mayhé Feb 10 '18 at 19:09
  • 10
    @JuniorM: Yes, you can make is static to reuse it, but you have to be careful so that you don't access it from multiple threads as it's not thread safe (as is usual for any class that is not specifically made thread safe). – Guffa Feb 13 '18 at 17:11
  • 46
    I think it would be useful to add a disclaimer that this is not cryptographically secure, since this is a popular question, just in case someone blindly tries to do cryptography with `Random`... – Daniel García Rubio Jun 27 '18 at 15:33
  • This throws a warning when using SonarQube: "Using pseudorandom number generators (PRNGs) is security-sensitive". – Machado Feb 05 '19 at 12:22
  • 3
    Excellent answer. There are some good "enhancements" to `Random` out there to make your random-ness more robust: https://ericlippert.com/2019/02/04/fixing-random-part-2/ and https://codeblog.jonskeet.uk/2009/11/04/revisiting-randomness/ . – Jesse C. Slicer Oct 08 '19 at 19:30
  • 2
    If it helps, var number = Random.Range(1, 254); from unity commutative: https://answers.unity.com/questions/308513/random-number-generator.html – Andres Mitre Feb 09 '20 at 01:19
  • 2
    In case anyone is confused, `rnd.Next(1,13)` includes 1 and excludes 13. i.e. lower bound is inclusive – dev27 Mar 10 '20 at 01:45
  • System.Random is not random! When running in a tight loop, it will create the same values over again. – cskwg Aug 16 '20 at 08:05
  • if you need the number to have a specific length, eg. 8 digits, you can do this: `rnd.Next(10000000, 99999999);` – volkit Dec 15 '20 at 10:36
  • @volkit: As the second operand is explusive, it should be `rnd.Next(10000000, 100000000)`. – Guffa Jan 02 '21 at 15:32
  • I tried: char RandomPass1 = (char)rnd.Next(1111, 99999); but I'm getting like a Chinese symbol. – KennyAli Feb 03 '21 at 02:52
  • @KennyAli: I don't know what you expected from that code. It doesn't make much sense, as the `char` data type can't hold a character code larger than 65535. Any value larger than that will be truncated and wrap around from zero, so your code effectively does the same thing as `(char)rnd.Next(0, 65536)`, only with a different distribution of the randomness. It gives you any random character from any character set, including chinese, japanese, cyrillic, greek, arabic, ethiopic, tai, georgian, cherokee, mongolian, runic and a lot more. – Guffa Feb 07 '21 at 12:05
  • 1
    @KennyAli: It will also give you combiation and surrogate codes that doesn't make sense on their own. Something that would make more sense is for example to create a character in the visible part of the ASCII character range: `(char)rnd.Next(32, 127)`. – Guffa Feb 07 '21 at 12:05
  • I'd add to the answer that you can seed the Random constructor with any value, thus you can either reconstruct the same random numbers sequence (i. e. if you want to have some reproducibility) or you can use a seed with better randomness (like asking a user to press keyboard/move mouse and take some arbitrary value from his actions). – montonero Jul 12 '21 at 15:25
400

The question looks very simple but the answer is bit complicated. If you see almost everyone has suggested to use the Random class and some have suggested to use the RNG crypto class. But then when to choose what.

For that we need to first understand the term RANDOMNESS and the philosophy behind it.

I would encourage you to watch this video that I made which goes in depth in the philosophy of RANDOMNESS using C# https://www.youtube.com/watch?v=tCYxc-2-3fY

First thing let us understand the philosophy of RANDOMNESS. When we tell a person to choose between RED, GREEN and YELLOW what happens internally. What makes a person choose RED or YELLOW or GREEN?

c# Random

Some initial thought goes into the persons mind which decides his choice, it can be favorite color , lucky color and so on. In other words some initial trigger which we term in RANDOM as SEED.This SEED is the beginning point, the trigger which instigates him to select the RANDOM value.

Now if a SEED is easy to guess then those kind of random numbers are termed as PSEUDO and when a seed is difficult to guess those random numbers are termed SECURED random numbers.

For example a person chooses is color depending on weather and sound combination then it would be difficult to guess the initial seed.

c# Random

Now let me make an important statement:-

*“Random” class generates only PSEUDO random number and to generate SECURE random number we need to use “RNGCryptoServiceProvider” class.

c# Random

Random class takes seed values from your CPU clock which is very much predictable. So in other words RANDOM class of C# generates pseudo random numbers , below is the code for the same.

Random random = new Random();
int randomNumber = random.Next();

While the RNGCryptoServiceProvider class uses OS entropy to generate seeds. OS entropy is a random value which is generated using sound, mouse click, and keyboard timings, thermal temp etc. Below goes the code for the same.

using (RNGCryptoServiceProvider rg = new RNGCryptoServiceProvider()) 
{ 
    byte[] rno = new byte[5];    
    rg.GetBytes(rno);    
    int randomvalue = BitConverter.ToInt32(rno, 0); 
}

To understand OS entropy see this video of mine starting at 14:30 https://www.youtube.com/watch?v=tCYxc-2-3fY where the logic of OS entropy is explained. So putting in simple words RNG Crypto generates SECURE random numbers.

Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
Shivprasad Koirala
  • 27,644
  • 7
  • 84
  • 73
  • 15
    shouldn't be your byte[5] only [4] as ToInt32 parses only 4 bytes? – Bernhard Nov 21 '17 at 11:34
  • 14
    It's always helpful to know where these classes live. System.Security.Cryptography – Elton Dec 18 '18 at 23:49
  • 10
    It is recommended to use `RandomNumberGenerator.Create()` instead of calling the constructor of `RNGCryptoServiceProvider` since it is not available on all platforms. – dzitkowskik Oct 17 '19 at 18:35
  • I want just to precise that SecureRandom IS pseudo random generation. – Nùménor Jan 29 '20 at 16:30
  • 1
    Due to the increased randomness of the seed, is it OK to create new RNGCryptoServiceProvider objects each time I need to generate a random number, or is it still better to create one RNGCryptoServiceProvider object and reuse it whenever I need to generate a random number, as should be done with the Random class? – user2150989 Mar 23 '20 at 17:24
275

Every time you do new Random() it is initialized. 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 random number
private static readonly Random getrandom = new Random();

public static int GetRandomNumber(int min, int max)
{
    lock(getrandom) // synchronize
    {
        return getrandom.Next(min, max);
    }
}
shA.t
  • 16,580
  • 5
  • 54
  • 111
Pankaj Mishra
  • 20,197
  • 16
  • 66
  • 103
  • 6
    Is this not what @Guffa said in his answer 6 months ago? "If you create new instances too close in time, they will produce the same series of random numbers" – Chris Oct 04 '10 at 12:00
  • 5
    @Chris- That's right what you said. In this I have provided the implementation of that. I think it's a good way of doing it. It works better. – Pankaj Mishra Oct 04 '10 at 14:16
  • 25
    This is an implementation that synchronises the code for use from seval threads. That is good for a multi threaded application, but a waste of time for a single threaded application. – Guffa Feb 26 '13 at 00:05
  • @SeanWorle: First, I tried it with the approach from Guffa. Then I tried to store the same `Random` object. At both cases I got the same random number. With the approach from Pankaj it didn't happen. Perhaps this is *random*, but I doubt it now. I'm querying for the random number in the same second from different threads. – testing Sep 12 '17 at 16:26
  • 4
    @testing: I agree that Pankaj's method is the correct one to use. What I'm saying is that it can be simplified to this: //Function to get random number private static readonly Random getrandom = new Random(); public static int GetRandomNumber(int min, int max) { lock(getrandom ) { // synchronize return getrandom.Next(min, max); } } – Sean Worle Sep 14 '17 at 01:51
128

Beware that new Random() is seeded on current timestamp.

If you want to generate just one number you can use:

new Random().Next( int.MinValue, int.MaxValue )

For more information, look at the Random class, though please note:

However, because the clock has finite resolution, using the parameterless constructor to create different Random objects in close succession creates random number generators that produce identical sequences of random numbers

So do not use this code to generate a series of random number.

Fyodor Soikin
  • 78,590
  • 9
  • 125
  • 172
  • 44
    -1: The default seed is based on time; do this in a loop and you'll get very non-random results. You should create **one** generator and use it for all your numbers, not a separate generator each time. – Bevan Apr 24 '10 at 23:39
  • 26
    Hey, that's unfair. The question was how to generate random int number. No loops or series were mentioned. – Fyodor Soikin Apr 25 '10 at 01:45
  • 28
    Ok, fair point. Rescinded. Though, I still think that not using `new Random()` in a loop is an important point. – Bevan Apr 25 '10 at 09:08
  • For those coming across this in the future, it should be obvious now, but I'll just point it out; the answer was updated with this point, to not use this in a loop for multiple values. – vapcguy Feb 14 '20 at 20:04
75
Random r = new Random();
int n = r.Next();
Joren
  • 14,472
  • 3
  • 50
  • 54
  • 3
    This seems an underrated valuable response!! – nilon Oct 11 '20 at 22:44
  • 3
    @nilon Well, depending on what OP - or a random reader like me - wants, this might be an overrated response. In my book, int is something between int.MinValue and int.MaxValue, but this call (in accordance with the documentation) never emits a negative number. – Eike Nov 12 '21 at 13:15
  • 4
    @Eike Since the OP didn't provide any details I also didn't feel the need to write a whole blog post. ‍♂️ – Joren Nov 19 '21 at 20:12
41

I wanted to add a cryptographically secure version:

RNGCryptoServiceProvider Class (MSDN or dotnetperls)

It implements IDisposable.

using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
{
   byte[] randomNumber = new byte[4];//4 for int32
   rng.GetBytes(randomNumber);
   int value = BitConverter.ToInt32(randomNumber, 0);
}
joordan831
  • 720
  • 5
  • 6
25

create a Random object

Random rand = new Random();

and use it

int randomNumber = rand.Next(min, max);

you don't have to initialize new Random() every time you need a random number, initiate one Random then use it as many times as you need inside a loop or whatever

Mohamed Ali
  • 3,717
  • 1
  • 33
  • 39
  • 7
    `new Random()` uses the current ticks as seed. When you instantiate multiple instances within the same millisecond (as opposed to tick), then you will get the same value returned. – Hans Kesting Apr 07 '17 at 14:09
  • 11
    This is actively bad. DateTime.Now.Millisecond (unlike DateTime.Now.Ticks) is a number between 0 and 999. If you're creating a new one of these for each random number, you'll only have 1000 possibilities. – Oren Melzer Aug 16 '18 at 22:47
  • What were 24 people thinking in up-voting this answer...? – Enigmativity May 15 '20 at 00:46
22

You could use Jon Skeet's StaticRandom method inside the MiscUtil class library that he built for a pseudo-random number.

using MiscUtil;
...

for (int i = 0; i < 100; 
    Console.WriteLine(StaticRandom.Next());
Lee Grissom
  • 9,705
  • 6
  • 37
  • 47
mbcrump
  • 974
  • 3
  • 7
  • 15
  • 34
    I just had a look at the source code, and this function uses exactly the same random number engine, the one "included" in C#, but makes sure that the same "seed"/"mother object" is used for all calls. (I am sorry that I do not know the C# terminology. But my point is that this function does not make any better random numbers than the standard function.) – Andreas Rejbrand Apr 25 '10 at 00:41
  • 6
    It's impossible for anything to be 'truly random' since there is always some limiting factor or prejudice included that is inherent by its very existence. Didn't you listen to the teacher in science classes? ;-) – Phill Healey Oct 15 '14 at 10:10
  • Let's say , according to him this is as 'truly random' as it gets – The Mitra Boy Aug 21 '15 at 07:42
18

I've tried all of these solutions excluding the COBOL answer... lol

None of these solutions were good enough. I needed randoms in a fast for int loop and I was getting tons of duplicate values even in very wide ranges. After settling for kind of random results far too long I decided to finally tackle this problem once and for all.

It's all about the seed.

I create a random integer by parsing out the non-digits from Guid, then I use that to instantiate my Random class.

public int GenerateRandom(int min, int max)
{
    var seed = Convert.ToInt32(Regex.Match(Guid.NewGuid().ToString(), @"\d+").Value);
    return new Random(seed).Next(min, max);
}

Update: Seeding isn't necessary if you instantiate the Random class once. So it'd be best to create a static class and call a method off that.

public static class IntUtil
{
   private static Random random;

   private static void Init()
   {
      if (random == null) random = new Random();
   }

   public static int Random(int min, int max)
   {
      Init();
      return random.Next(min, max);
   }
}

Then you can use the static class like so..

for(var i = 0; i < 1000; i++)
{
   int randomNumber = IntUtil.Random(1,100);
   Console.WriteLine(randomNumber); 
}

I admit I like this approach better.

Proximo
  • 6,235
  • 11
  • 49
  • 67
  • 8
    Guid is not random, it is not a good seed. A GUID doesn't make guarantees about randomness, it makes guarantees around uniqueness. http://stackoverflow.com/questions/2621563/how-random-is-system-guid-newguid-take-two – Markus Oct 11 '15 at 19:02
  • 3
    Guid is a good seed. I am only using the numbers in the Guid. Try the method for yourself. Put it in a long for loop and look at the results for yourself. – Proximo Oct 11 '15 at 23:29
  • 2
    Hmm, on second thought.. seed isn't necessary at all. Updating answer – Proximo Oct 11 '15 at 23:49
  • 3
    Great point on the update. I didn't even think to make it a static field, this way works much better and is cleaner. – JCisar Aug 19 '16 at 18:53
  • 2
    There are some problems with this answer. First of all GUID is not a great seed source - just because it looks random doesn't mean it is. It *may* be good enough for your personal needs. Secondly the Random class isn't thread safe. You need to instantiate it once per thread. – Hector Oct 10 '17 at 07:43
  • 1
    Well, as per your comment, put it in a long loop and see for yourself... And no, 1000 times is not a 'long loop' :) – Bartosz Jul 27 '19 at 21:41
  • 1
    @Proximo - There is no certainty that Guid will have random digits. They way Guids have been computed has changed many times and there is no guarantee that it will remain the same going forward. – Enigmativity May 15 '20 at 00:45
  • 1
    @Proximo - Yes, but your answer still has the `Guid` code in there. – Enigmativity May 26 '20 at 02:39
  • @Enigmativity Using the GUID was my original answer. I updated and completely changed it to using a static singleton class. They are two different answers, and if you read I say that I prefer the second approach better. – Proximo May 27 '20 at 05:58
  • 1
    @Proximo - The fact that it's still there is the issue. I'm suggesting it's a bad answer. Even a `private static Random random;` is bad. It should be `[ThreadStatic] private static Random random;` to be safer. – Enigmativity May 27 '20 at 09:35
  • 1
    @Proximo - It's the community's responsibility to improve the quality of all questions and answers on this site. I'm just trying to suggest improvements to your answer. Please don't feel personally harassed. I do share the love elsewhere. – Enigmativity May 28 '20 at 22:14
  • @Enigmativity if you want to add a suggestion just do that, no need for the toxicity. – Proximo May 31 '20 at 06:14
  • 1
    @Proximo - I have made a suggestion. Can you please let me know where in my comments there is any toxicity? – Enigmativity May 31 '20 at 07:57
  • @Proximo - It's not beside the point as your answer still starts off recommending the use of a `Guid` for the seed. You shouldn't someone to read the full answer. How is it that you feel I'm saving face with the `ThreadStatic` suggestion? What insult? And even when you read the full answer it does not say that `Guid`s are bad - it just suggests an edge case. – Enigmativity May 31 '20 at 09:44
  • @Enigmativity you keep deleting my comments on my own answer. This one-sided conversation is over. – Proximo Jun 01 '20 at 14:05
  • @Proximo - I'm not deleting anything. – Enigmativity Jun 02 '20 at 01:35
  • @Proximo - If any of your comments are being deleted, is it possible that you're violating the system etiquette and the mods are deleting them? You're sounding angry. I'd like to understand why? – Enigmativity Jun 02 '20 at 01:40
18

As described in other answers, a good secured approach would be to use a secure cryptographic generator. All examples here show the usage of RNGCryptoServiceProvider which is writing a long code compared to the solution I suggest.

Use RandomNumberGenerator which is written on top of cryptography API’s. It is as secure as RNGCryptoServiceProvider and same randomness.

// Gives a random number for the integer range.
// You can simply update the parameters as your needs.
RandomNumberGenerator.GetInt32(int.MinValue, int.MaxValue);
Misha Zaslavsky
  • 8,414
  • 11
  • 70
  • 116
15

Modified answer from here.

If you have access to an Intel Secure Key compatible CPU, you can generate real random numbers and strings using these libraries: https://github.com/JebteK/RdRand and https://www.rdrand.com/

Just download the latest version from here, include Jebtek.RdRand and add a using statement for it. Then, all you need to do is this:

// Check to see if this is a compatible CPU
bool isAvailable = RdRandom.GeneratorAvailable();

// Generate 10 random characters
string key       = RdRandom.GenerateKey(10);

 // Generate 64 random characters, useful for API keys 
string apiKey    = RdRandom.GenerateAPIKey();

// Generate an array of 10 random bytes
byte[] b         = RdRandom.GenerateBytes(10);

// Generate a random unsigned int
uint i           = RdRandom.GenerateUnsignedInt();

If you don't have a compatible CPU to execute the code on, just use the RESTful services at rdrand.com. With the RdRandom wrapper library included in your project, you would just need to do this (you get 1000 free calls when you signup):

string ret = Randomizer.GenerateKey(<length>, "<key>");
uint ret   = Randomizer.GenerateUInt("<key>");
byte[] ret = Randomizer.GenerateBytes(<length>, "<key>");
Matt
  • 25,467
  • 18
  • 120
  • 187
JebaDaHut
  • 541
  • 5
  • 11
15

The numbers generated by the inbuilt Random class (System.Random) generates pseudo random numbers.

If you want true random numbers, the closest we can get is "secure Pseudo Random Generator" which can be generated by using the Cryptographic classes in C# such as RNGCryptoServiceProvider.

Even so, if you still need true random numbers you will need to use an external source such as devices accounting for radioactive decay as a seed for an random number generator. Since, by definition, any number generated by purely algorithmic means cannot be truly random.

Anshita Arya
  • 181
  • 1
  • 6
12

Just as a note for future reference.

If you're using .NET Core, multiple Random instances aren't as dangerous as before. I'm aware that this question is from 2010, but since this question is old but has some attraction, I think it's a good thing to document the change.

You may refer to this question I made a while back:

Did Microsoft change Random default seed?

Basically, they have changed the default seed from Environment.TickCount to Guid.NewGuid().GetHashCode(), so if you create 2 instances of Random it shouldn't display the same numbers (1:4 billion).

You can see the file diffs from .NET Framework/.NET Core (2.0.0+) here: https://github.com/dotnet/coreclr/pull/2192/commits/9f6a0b675e5ac0065a268554de49162c539ff66d

It isn't as safe as RNGCryptoServiceProvider, but at least it won't give you weird results.


By @Enigmativity:

This is now out-of-date. There was a considerable backlash against using Guids. The code is now Interop.GetRandomBytes((byte*)&result, sizeof(int));

Lucca Ferri
  • 1,308
  • 12
  • 23
  • 2
    This is now out-of-date. There was a considerable backlash against using Guids. The code is now `Interop.GetRandomBytes((byte*)&result, sizeof(int));`. – Enigmativity May 15 '20 at 00:54
7

This is the class I use. Works like RandomNumber.GenerateRandom(1, 666)

internal static class RandomNumber
{
    private static Random r = new Random();
    private static object l = new object();
    private static Random globalRandom = new Random();
    [ThreadStatic]
    private static Random localRandom;
    public static int GenerateNewRandom(int min, int max)
    {
        return new Random().Next(min, max);
    }
    public static int GenerateLockedRandom(int min, int max)
    {
        int result;
        lock (RandomNumber.l)
        {
            result = RandomNumber.r.Next(min, max);
        }
        return result;
    }
    public static int GenerateRandom(int min, int max)
    {
        Random random = RandomNumber.localRandom;
        if (random == null)
        {
            int seed;
            lock (RandomNumber.globalRandom)
            {
                seed = RandomNumber.globalRandom.Next();
            }
            random = (RandomNumber.localRandom = new Random(seed));
        }
        return random.Next(min, max);
    }
}
MechMK1
  • 3,278
  • 7
  • 37
  • 55
AskethZ
  • 87
  • 1
  • 1
  • Your GenerateRandom class will never return the number 666, only 665. This is common misunderstanding (feature) of Random.Next max value. – Gordon Bell Jul 26 '16 at 16:59
6

While this is okay:

Random random = new Random();
int randomNumber = random.Next()

You'd want to control the limit (min and max mumbers) most of the time. So you need to specify where the random number starts and ends.

The Next() method accepts two parameters, min and max.

So if i want my random number to be between say 5 and 15, I'd just do

int randomNumber = random.Next(5, 16)
Gordon Bell
  • 13,337
  • 3
  • 45
  • 64
Ojonugwa Jude Ochalifu
  • 26,627
  • 26
  • 120
  • 132
5

I wanted to demonstrate what happens when a new random generator is used every time. Suppose you have two methods or two classes each requiring a random number. And naively you code them like:

public class A
{
    public A()
    {
        var rnd=new Random();
        ID=rnd.Next();
    }
    public int ID { get; private set; }
}
public class B
{
    public B()
    {
        var rnd=new Random();
        ID=rnd.Next();
    }
    public int ID { get; private set; }
}

Do you think you will get two different IDs? NOPE

class Program
{
    static void Main(string[] args)
    {
        A a=new A();
        B b=new B();

        int ida=a.ID, idb=b.ID;
        // ida = 1452879101
        // idb = 1452879101
    }
}

The solution is to always use a single static random generator. Like this:

public static class Utils
{
    public static readonly Random random=new Random();
}

public class A
{
    public A()
    {
        ID=Utils.random.Next();
    }
    public int ID { get; private set; }
}
public class B
{
    public B()
    {
        ID=Utils.random.Next();
    }
    public int ID { get; private set; }
}
John Alexiou
  • 28,472
  • 11
  • 77
  • 133
  • How do you safely choose a seed then? – John Alexiou Apr 11 '16 at 02:28
  • Well, first, if your objects are created even 10 ms apart, the random numbers generated are different with the default seed. Second, you can mash whatever random environmental or process data you have around to get a seed. Then there's the tradeoff of whether you want one long sequence of numbers that will most likely start repeating itself, or multiple streams even if two streams end up being identical. And if you're concerned about security, `RNGCryptoServiceProvider` is a better call anyway. – Millie Smith Apr 11 '16 at 02:59
  • It would be cool to have a randomizer chip with a small alpha particle radioactive source and a detector (how smoke detector works) in order to randomize numbers based on radioactive decay (which is very random). – John Alexiou Apr 11 '16 at 13:01
5

In .NET 6 you can use Random.Shared:

int random = Random.Shared.Next();

And in .NET 8 preview this class was added with many new missing methods, e.g. Shuffle array randomly, etc.

Misha Zaslavsky
  • 8,414
  • 11
  • 70
  • 116
4

Numbers calculated by a computer through a deterministic process, cannot, by definition, be random.

If you want a genuine random numbers, the randomness comes from atmospheric noise or radioactive decay.

You can try for example RANDOM.ORG (it reduces performance)

Stefano Lonati
  • 704
  • 6
  • 15
4

For strong random seed I always use CryptoRNG and not Time.

using System;
using System.Security.Cryptography;

public class Program
{
    public static void Main()
    {
        var random = new Random(GetSeed());
        Console.WriteLine(random.Next());
    }

    public static int GetSeed() 
    {
        using (var rng = new RNGCryptoServiceProvider())
        {
            var intBytes = new byte[4];
            rng.GetBytes(intBytes);
            return BitConverter.ToInt32(intBytes, 0);
        }
    }
}
Davit Tvildiani
  • 1,915
  • 3
  • 19
  • 29
  • You're using one random number generator to get the seed for another? If you need a "strong" seed then wouldn't you want (cryptographically) strong numbers output as well? Why not just use `RNGCryptoServiceProvider` for everything at this point? – Lance U. Matthews Feb 20 '22 at 03:33
3
Random rand = new Random();
int name = rand.Next()

Put whatever values you want in the second parentheses make sure you have set a name by writing prop and double tab to generate the code

shA.t
  • 16,580
  • 5
  • 54
  • 111
3
Random random = new Random ();
int randomNumber = random.Next (lowerBound,upperBound);
Andrius Naruševičius
  • 8,348
  • 7
  • 49
  • 78
ReRoute
  • 371
  • 1
  • 13
  • 1
    While this code may answer the question, it is better to explain how to solve the problem and provide the code as an example or reference. Code-only answers can be confusing and lack context. – Robert Columbia Aug 22 '18 at 00:30
3

If you want a CSRNG to generate random numbers between a min and max, this is for you. It will initialize Random classes with secure random seeds.

    class SecureRandom : Random
    {
        public static byte[] GetBytes(ulong length)
        {
            RNGCryptoServiceProvider RNG = new RNGCryptoServiceProvider();
            byte[] bytes = new byte[length];
            RNG.GetBytes(bytes);
            RNG.Dispose();
            return bytes;
        }
        public SecureRandom() : base(BitConverter.ToInt32(GetBytes(4), 0))
        {

        }
        public int GetRandomInt(int min, int max)
        {
            int treashold = max - min;
            if(treashold != Math.Abs(treashold))
            {
                throw new ArithmeticException("The minimum value can't exceed the maximum value!");
            }
            if (treashold == 0)
            {
                throw new ArithmeticException("The minimum value can't be the same as the maximum value!");
            }
            return min + (Next() % treashold);
        }
        public static int GetRandomIntStatic(int min, int max)
        {
            int treashold = max - min;
            if (treashold != Math.Abs(treashold))
            {
                throw new ArithmeticException("The minimum value can't exceed the maximum value!");
            }
            if(treashold == 0)
            {
                throw new ArithmeticException("The minimum value can't be the same as the maximum value!");
            }
            return min + (BitConverter.ToInt32(GetBytes(4), 0) % treashold);
        }
    }
Jessie Lesbian
  • 1,273
  • 10
  • 14
2

I will assume that you want a uniformly distributed random number generator like below. Random number in most of programming language including C# and C++ is not properly shuffled before using them. This means that you will get the same number over and over, which isn't really random. To avoid to draw the same number over and over, you need a seed. Typically, ticks in time is ok for this task. Remember that you will get the same number over and over if you are using the same seed every time. So try to use varying seed always. Time is a good source for seed because they chage always.

int GetRandomNumber(int min, int max)
{
    Random rand = new Random((int)DateTime.Now.Ticks);
    return rand.Next(min, max);
}

if you are looking for random number generator for normal distribution, you might use a Box-Muller transformation. Check the answer by yoyoyoyosef in Random Gaussian Variable Question. Since you want integer, you have to cast double value to integer at the end.

Random rand = new Random(); //reuse this if you are generating many
double u1 = 1.0-rand.NextDouble(); //uniform(0,1] random doubles
double u2 = 1.0-rand.NextDouble();
double randStdNormal = Math.Sqrt(-2.0 * Math.Log(u1)) *
         Math.Sin(2.0 * Math.PI * u2); //random normal(0,1)
double randNormal =
         mean + stdDev * randStdNormal; //random normal(mean,stdDev^2)

Random Gaussian Variables

auto9817
  • 153
  • 3
  • 12
2

Sorry, OP indeed requires a random int value, but for the simple purpose to share knowledge if you want a random BigInteger value you can use following statement:

BigInteger randomVal = BigInteger.Abs(BigInteger.Parse(Guid.NewGuid().ToString().Replace("-",""), NumberStyles.AllowHexSpecifier));
Ciro Corvino
  • 2,038
  • 5
  • 20
  • 33
  • 1
    I think you'd do better to use `byte[] bytes = new byte[byteCount]; random.NextBytes(bytes); BigInteger value = new BigInteger(bytes);` or use repeated calls to `Random.Next((int) '0', ((int) '9') + 1)` to build a `string` of random digits and parse that instead. This (ab)usage of `Guid` is unorthodox and pretty much guaranteed to _only_ return astronomically-large numbers (so not really "random"). Further, [the documentation](https://docs.microsoft.com/dotnet/api/system.guid.newguid#remarks) recommends "... that applications **not** use the `NewGuid` method for cryptographic purposes." – Lance U. Matthews Feb 20 '22 at 05:38
2

There are a number utility functions or services that are better cached in the same way that System.Random should be, so it lends itself to a generic implementation:

static public class CachedService<T> where T : new() {
    static public T Get { get; } = new T();
}

To use for random (or similar):

CachedService<System.Random>.Get.Next(999);
Matt Parkins
  • 24,208
  • 8
  • 50
  • 59
-1

The Random class is used for generating a pseudo-random number. An example could be like this:

public int GenRandom(int minimum, int maximum)
{
    Random random = new Random();
    int result = random.Next(minimum - 1, maximum + 1);
    return result;
}

I added 1 to the minimum and maximum because the Next(int, int) function can never reach minimum and maximum.

Also look at this, would be a random number guesser:

class Program
{
    static void Main(string[] args)
    {
        int i = 0;
        while (true)
        {
            if (i < 1)
            {
                Console.Write("Minimum value: ");
                int min = int.Parse(Console.ReadLine());
                Console.Write("Maximum value: ");
                int max = int.Parse(Console.ReadLine());
                Random random = new Random();
            }
            int randomNumber = random.Next(min, max);
            Console.Write("Enter a guess: ");
            if (int.Parse(Console.ReadLine()) == randomNumber)
            {
                Console.WriteLine("Congrats! You won!");
                Console.ReadKey();
                return;
            }
            else
                Console.WriteLine("Hmm, give it another guess!"); return;
        }
    }
}
-2

Why not use int randomNumber = Random.Range(start_range, end_range) ?

Recomer
  • 178
  • 2
  • 12
  • Actually int randomNumber = Random.Range(start_range, end_range + 1) – Gordon Bell Jul 26 '16 at 17:09
  • 5
    Does Random.Range() exist? I couldn't find it in the MSDN documentation. – Phillip Ngan Sep 01 '16 at 10:17
  • This appears to be [specific to Unity](https://docs.unity3d.com/ScriptReference/Random.Range.html). If so, it'd be helpful to state that and explain [how it compares to `System.Random`](https://docs.unity3d.com/ScriptReference/Random.html). – Lance U. Matthews Feb 20 '22 at 03:52
-2

Use one instance of Random repeatedly

// Somewhat better code...
Random rng = new Random();
for (int i = 0; i < 100; i++)
{
    Console.WriteLine(GenerateDigit(rng));
}
...
static int GenerateDigit(Random rng)
{
    // Assume there'd be more logic here really
    return rng.Next(10);
}

This article takes a look at why randomness causes so many problems, and how to address them. http://csharpindepth.com/Articles/Chapter12/Random.aspx

  • `Random` isn't a thread safe class. If you create a single instance, you should restrict access to it behind a locking mechanism. – Brad M Jan 24 '19 at 17:59
-2
Random r=new Random();
int Numbers=r.next(min value, max value);
Masiha
  • 1
  • 2
  • 1
    The method is named `Next`, not `next`, so this won't compile. Further, the upper bound parameter is _exclusive_, so the largest number `r.Next(minValue, maxValue);` will return is actually `maxValue - 1`. `Numbers` is a bad name, too, for a variable storing a single number. Finally, and mostly importantly, this basic usage of the `Random` class has been covered by numerous other answers. – Lance U. Matthews Feb 20 '22 at 04:04
-3

Try these simple steps to create random numbers:

Create function:

private int randomnumber(int min, int max)
{
    Random rnum = new Random();
    return rnum.Next(min, max);
}

Use the above function in a location where you want to use random numbers. Suppose you want to use it in a text box.

textBox1.Text = randomnumber(0, 999).ToString();

0 is min and 999 is max. You can change the values to whatever you want.

glennsl
  • 28,186
  • 12
  • 57
  • 75
Hani Mehdi
  • 187
  • 4
  • 9
  • This will return the same number when called multiple times closely together as it uses System time as a seed... – MOnsDaR Apr 12 '16 at 19:04
  • 2
    randomnumber(0, 999) will never return 999. Max Value is not inclusive. This is common misunderstanding (feature) of Random.Next max value. – Gordon Bell Jul 26 '16 at 17:15
-3

I always have methods that generate random numbers which help for various purposes. I hope this may help you too:

public class RandomGenerator  
{  
    public int RandomNumber(int min, int max)  
    {  
        var random = new Random();  
        return random.Next(min, max);  
    }  

    public string RandomString(int size, bool lowerCase)  
    {  
        var builder = new StringBuilder();  
        var random  = new Random();  
        char ch;  

        for (int i = 0; i < size; i++)  
        {  
            ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));  
            builder.Append(ch);  
        }  

        if (lowerCase)  
            return builder.ToString().ToLower();  
        return builder.ToString();  
    }  
}
AustinWBryan
  • 3,249
  • 3
  • 24
  • 42
PatsonLeaner
  • 1,230
  • 15
  • 26
-4

Quick and easy for inline, use bellow code:

new Random().Next(min, max);

// for example unique name
strName += "_" + new Random().Next(100, 999);
Zolfaghari
  • 1,259
  • 1
  • 15
  • 14
-5
 int n = new Random().Next();

You can also give minimum and maximum value to Next() function. Like:

 int n = new Random().Next(5, 10);
AustinWBryan
  • 3,249
  • 3
  • 24
  • 42
Muhammad Awais
  • 4,238
  • 1
  • 42
  • 37