To generate a random number in C#, either use Random.Next in the System namespace, or the RandomNumberGenerator.GetInt32 function in the System.Security.Cryptography namespace.

In the first version, we instantiate a Random object (from the System namespace) on line 1 and use it on line 7 to get a random number from 1 to 10. Notice that the second parameter is 11, not 10. This maxValue parameter needs to be one number higher than the highest number you want the function to return.

So, if you want a random number from 1 to 6 (like rolling dice), you need to use 1 and 7 for the parameters.

On lines 10-11 we add the value to a dictionary so we can count the how many times each number was returned.

Then, on lines 14-17 we write a count of each value that was returned and how many times the function returned it. This is to verify the code is actually doing what we want it to do and that the distribution of values is random.

var random = new Random(); Dictionary<int, int> results = new Dictionary<int, int>(); for(int i = 0; i < 10000; i++) { var value = random.Next(1, 11); // Add the value to a Dictionary to see how many times we got the value if(!results.ContainsKey(value)) { results.Add(value, 0); } results[value]++; } foreach(var result in results.OrderBy(r => r.Key)) { Console.WriteLine($"{result.Key} : {result.Value}"); }

If you want the random number to be more “random”, you can use the code below – which uses the RandomNumberGenerator.GetInt32 function from the System.Security.Cryptography namespace.

To use this function, you need to include the using directive on line 1.

On line 7, we get the random number. Just like with the Random class, the maxValue parameter needs to be one larger than the maximum value you want the function to return.

using System.Security.Cryptography; Dictionary<int, int> results = new Dictionary<int, int>(); for(int i = 0; i < 10000 ; i++) { var value = RandomNumberGenerator.GetInt32(1, 11); // Add the value to a Dictionary to see how many times we got the value if(!results.ContainsKey(value)) { results.Add(value, 0); } results[value]++; } foreach(var result in results.OrderBy(r => r.Key)) { Console.WriteLine($"{result.Key} : {result.Value}"); }