Random Number In C# And .NET Core

The Random class of .NET class library provides functionality to generate random numbers in C#. This article demonstrates how to create an int random number and random strings in C# and .NET Core using the Random class. 

Figure 1 is an example of a random number and random string.

Random Number In C# and .NET Core
Figure 1.

The Random class constructors have two overloaded forms. It takes either no value or it takes a seed value.

The Random class has three public methods - Next, NextBytes, and NextDouble. The Next method returns a random number, NextBytes returns an array of bytes filled with random numbers, and NextDouble returns a random number between 0.0 and 1.0.

Generate a random int

The following code in Listing 1 returns a random number.

  1. // Generate a random number  
  2. Random random = new Random();  
  3. // Any random integer   
  4. int num = random.Next();  

Listing 1.

Generate a random number less than a number

The Next method has three overloaded forms and allows you to set the minimum and maximum range of the random number.

By passing a single maximum value to the Next method, the method generates a random number less than the max value passed in the method. The following code snippet in Listing 2 returns a random number that is less than 100.

  1. // A random number below 100  
  2. int randomLessThan100 = random.Next(100);  
  3. Console.WriteLine(randomLessThan100);  

Listing 2.

Generate a random number within a range

The Next method of the Random class takes a minimum and maximum value and generates a random number between the two values. The following code snippet in Listing 3 returns a random number between numbers 100 and 500.

  1. // A random number within a range  
  2. int randomBetween100And500 = random.Next(100, 500);  
  3. Console.WriteLine(randomBetween100And500);  

Listing 3.

How to generate a random string

The following code snippet in Listing 4 generates a random string with a given size. The second parameter of the RandomString method is used for setting if the string is a lowercase string.

  1. // Generate a random string with a given size and case.   
  2. // If second parameter is true, the return string is lowercase  
  3. public string RandomString(int size, bool lowerCase)  
  4. {  
  5.     StringBuilder builder = new StringBuilder();  
  6.     Random random = new Random();  
  7.     char ch;  
  8.     for (int i = 0; i < size; i++)  
  9.     {  
  10.         ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));  
  11.         builder.Append(ch);  
  12.     }  
  13.     if (lowerCase)  
  14.         return builder.ToString().ToLower();  
  15.     return builder.ToString();  
  16. }  

Listing 4.

The following code method in Listing 5 generates a random number within a range.

  1. // Generate a random number between two numbers    
  2. public int RandomNumber(int min, int max)  
  3. {  
  4.     Random random = new Random();  
  5.     return random.Next(min, max);  
  6. }  

Listing 5.

Creating a random password combination of strings and numbers

You can even combine the two methods - RandomNumber and RandomString to generate a combination of random string and numbers.

The following code snippet in Listing 6 generates a password of length 10 with first 4 letters lowercase, next 4 letters numbers, and last 2 letters as uppercase.

  1. // Generate a random password of a given length (optional)  
  2. public string RandomPassword(int size = 0)  
  3. {  
  4.     StringBuilder builder = new StringBuilder();  
  5.     builder.Append(RandomString(4, true));  
  6.     builder.Append(RandomNumber(1000, 9999));  
  7.     builder.Append(RandomString(2, false));  
  8.     return builder.ToString();  
  9. }  

Listing 6.

All of the above functionality is listed here in Listing 7. Create a .NET Core Console app in Visual Studio and use this code.

  1. using System;  
  2. using System.Text;  
  3.   
  4. class RandomNumberSample  
  5. {  
  6.     static void Main(string[] args)  
  7.     {  
  8.         // Generate a random number  
  9.         Random random = new Random();  
  10.         // Any random integer   
  11.         int num = random.Next();  
  12.   
  13.         // A random number below 100  
  14.         int randomLessThan100 = random.Next(100);  
  15.         Console.WriteLine(randomLessThan100);  
  16.   
  17.         // A random number within a range  
  18.         int randomBetween100And500 = random.Next(100, 500);  
  19.         Console.WriteLine(randomBetween100And500);  
  20.   
  21.         // Use other methods   
  22.         RandomNumberGenerator generator = new RandomNumberGenerator();  
  23.         int rand = generator.RandomNumber(5, 100);  
  24.         Console.WriteLine($"Random number between 5 and 100 is {rand}");  
  25.   
  26.         string str = generator.RandomString(10, false);  
  27.         Console.WriteLine($"Random string of 10 chars is {str}");  
  28.   
  29.         string pass = generator.RandomPassword();  
  30.         Console.WriteLine($"Random password {pass}");  
  31.   
  32.         Console.ReadKey();  
  33.     }  
  34. }  
  35.   
  36. public class RandomNumberGenerator  
  37. {  
  38.     // Generate a random number between two numbers    
  39.     public int RandomNumber(int min, int max)  
  40.     {  
  41.         Random random = new Random();  
  42.         return random.Next(min, max);  
  43.     }  
  44.   
  45. // Generate a random string with a given size and case.   
  46. // If second parameter is true, the return string is lowercase  
  47. public string RandomString(int size, bool lowerCase)  
  48. {  
  49.     StringBuilder builder = new StringBuilder();  
  50.     Random random = new Random();  
  51.     char ch;  
  52.     for (int i = 0; i < size; i++)  
  53.     {  
  54.         ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));  
  55.         builder.Append(ch);  
  56.     }  
  57.     if (lowerCase)  
  58.         return builder.ToString().ToLower();  
  59.     return builder.ToString();  
  60. }  
  61.   
  62.     // Generate a random password of a given length (optional)  
  63.     public string RandomPassword(int size = 0)  
  64.     {  
  65.         StringBuilder builder = new StringBuilder();  
  66.         builder.Append(RandomString(4, true));  
  67.         builder.Append(RandomNumber(1000, 9999));  
  68.         builder.Append(RandomString(2, false));  
  69.         return builder.ToString();  
  70.     }  
  71. }  

Listing 7.

The random string and random password look like Figure 2.

Random Number In C# and .NET Core
Figure 2.

How to select a random string from an array of strings

This article demonstrates how to pick a random string and array of strings.

We can use the random number generator to pick a random item from an array. The following code snippet has an array of author names (strings). We can pick a random author by generating a random number that is less than the number of items in the array and use the random index to pick a random author name in the string.

The Random.Next method generates a random integer and by passing the maximum length of the array means the random number cannot be greater than the number of items in the array.

See Listing 8.

  1. using System;  
  2. public class RandomStringInArraySample  
  3. {  
  4.     public static void Main()  
  5.     {  
  6.         // A array of authors   
  7.         string[] authors = { "Mahesh Chand""Jeff Prosise""Dave McCarter""Allen O'neill",  
  8.                                 "Monica Rathbun""Henry He""Raj Kumar""Mark Prime",  
  9.                                 "Rose Tracey""Mike Crown" };  
  10.   
  11.         // Create a Random object  
  12.         Random rand = new Random();  
  13.         // Generate a random index less than the size of the array.  
  14.         int index = rand.Next(authors.Length);  
  15.     
  16.         // Display the result.        
  17.         Console.WriteLine($"Randomly selected author is  {authors[index]}");  
  18.   
  19.         Console.ReadKey();  
  20.     }  
  21. }  

Listing 8.

Summary

In this tutorial, we discussed how to generate random numbers, random strings, and random passwords in C# and .NET Core. We also saw how we can select an item from an array randomly.

How To Generate A Random Password In C# and .NET Core

A random password is a combination of characters, numbers, and special characters. We can generate a random password by combining random numbers and random strings.

The code snippet in this article is an example of how to generate random numbers and random strings and combine them to create a random password using C# and .NET Core.

The Random class constructors have two overloaded forms. It takes either no value or it takes a seed value.

The Random class has three public methods - Next, NextBytes, and NextDouble. The Next method returns a random number, NextBytes returns an array of bytes filled with random numbers, and NextDouble returns a random number between 0.0 and 1.0.

Generate a random number

The following code in Listing 1 returns a random number.

  1. // Generate a random number  
  2. Random random = new Random();  
  3. // Any random integer   
  4. int num = random.Next();  

Listing 1.

How to generate a random string

The following code snippet in Listing 4 generates a random string with a given size. The second parameter of the RandomString method is used for setting if the string is a lowercase string.

  1. // Generate a random string with a given size and case.   
  2. // If second parameter is true, the return string is lowercase  
  3. public string RandomString(int size, bool lowerCase)  
  4. {  
  5.     StringBuilder builder = new StringBuilder();  
  6.     Random random = new Random();  
  7.     char ch;  
  8.     for (int i = 0; i < size; i++)  
  9.     {  
  10.         ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));  
  11.         builder.Append(ch);  
  12.     }  
  13.     if (lowerCase)  
  14.         return builder.ToString().ToLower();  
  15.     return builder.ToString();  
  16. }  

Listing 4.

Creating a random password combination of strings and numbers

You can even combine the two methods - RandomNumber and RandomString to generate a combination of random string and numbers.

The following code snippet in Listing 6 generates a password of length 10 with first 4 letters lowercase, next 4 letters numbers, and last 2 letters as uppercase.

  1. // Generate a random password of a given length (optional)  
  2. public string RandomPassword(int size = 0)  
  3. {  
  4.     StringBuilder builder = new StringBuilder();  
  5.     builder.Append(RandomString(4, true));  
  6.     builder.Append(RandomNumber(1000, 9999));  
  7.     builder.Append(RandomString(2, false));  
  8.     return builder.ToString();  
  9. }  

Listing 6.

All of the above functionality is listed here in Listing 7. Create a .NET Core Console app in Visual Studio and use this code.

  1. using System;  
  2. using System.Text;  
  3.   
  4. class RandomNumberSample  
  5. {  
  6.     static void Main(string[] args)  
  7.     {  
  8.         // Generate a random number  
  9.         Random random = new Random();  
  10.         // Any random integer   
  11.         int num = random.Next();  
  12.   
  13.         // A random number below 100  
  14.         int randomLessThan100 = random.Next(100);  
  15.         Console.WriteLine(randomLessThan100);  
  16.   
  17.         // A random number within a range  
  18.         int randomBetween100And500 = random.Next(100, 500);  
  19.         Console.WriteLine(randomBetween100And500);  
  20.   
  21.         // Use other methods   
  22.         RandomNumberGenerator generator = new RandomNumberGenerator();  
  23.         int rand = generator.RandomNumber(5, 100);  
  24.         Console.WriteLine($"Random number between 5 and 100 is {rand}");  
  25.   
  26.         string str = generator.RandomString(10, false);  
  27.         Console.WriteLine($"Random string of 10 chars is {str}");  
  28.   
  29.         string pass = generator.RandomPassword();  
  30.         Console.WriteLine($"Random password {pass}");  
  31.   
  32.         Console.ReadKey();  
  33.     }  
  34. }  
  35.   
  36. public class RandomNumberGenerator  
  37. {  
  38.     // Generate a random number between two numbers    
  39.     public int RandomNumber(int min, int max)  
  40.     {  
  41.         Random random = new Random();  
  42.         return random.Next(min, max);  
  43.     }  
  44.   
  45. // Generate a random string with a given size and case.   
  46. // If second parameter is true, the return string is lowercase  
  47. public string RandomString(int size, bool lowerCase)  
  48. {  
  49.     StringBuilder builder = new StringBuilder();  
  50.     Random random = new Random();  
  51.     char ch;  
  52.     for (int i = 0; i < size; i++)  
  53.     {  
  54.         ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));  
  55.         builder.Append(ch);  
  56.     }  
  57.     if (lowerCase)  
  58.         return builder.ToString().ToLower();  
  59.     return builder.ToString();  
  60. }  
  61.   
  62.     // Generate a random password of a given length (optional)  
  63.     public string RandomPassword(int size = 0)  
  64.     {  
  65.         StringBuilder builder = new StringBuilder();  
  66.         builder.Append(RandomString(4, true));  
  67.         builder.Append(RandomNumber(1000, 9999));  
  68.         builder.Append(RandomString(2, false));  
  69.         return builder.ToString();  
  70.     }  
  71. }  

Listing 7.

The random string and random password look like Figure 2.

Random Number In C# and .NET Core
Figure 2.


Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.