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.
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.
-
- Random random = new Random();
-
- 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.
-
- int randomLessThan100 = random.Next(100);
- 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.
-
- int randomBetween100And500 = random.Next(100, 500);
- 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.
-
-
- public string RandomString(int size, bool lowerCase)
- {
- StringBuilder builder = new StringBuilder();
- Random 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();
- }
Listing 4.
The following code method in Listing 5 generates a random number within a range.
-
- public int RandomNumber(int min, int max)
- {
- Random random = new Random();
- return random.Next(min, max);
- }
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.
-
- public string RandomPassword(int size = 0)
- {
- StringBuilder builder = new StringBuilder();
- builder.Append(RandomString(4, true));
- builder.Append(RandomNumber(1000, 9999));
- builder.Append(RandomString(2, false));
- return builder.ToString();
- }
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.
- using System;
- using System.Text;
-
- class RandomNumberSample
- {
- static void Main(string[] args)
- {
-
- Random random = new Random();
-
- int num = random.Next();
-
-
- int randomLessThan100 = random.Next(100);
- Console.WriteLine(randomLessThan100);
-
-
- int randomBetween100And500 = random.Next(100, 500);
- Console.WriteLine(randomBetween100And500);
-
-
- RandomNumberGenerator generator = new RandomNumberGenerator();
- int rand = generator.RandomNumber(5, 100);
- Console.WriteLine($"Random number between 5 and 100 is {rand}");
-
- string str = generator.RandomString(10, false);
- Console.WriteLine($"Random string of 10 chars is {str}");
-
- string pass = generator.RandomPassword();
- Console.WriteLine($"Random password {pass}");
-
- Console.ReadKey();
- }
- }
-
- public class RandomNumberGenerator
- {
-
- public int RandomNumber(int min, int max)
- {
- Random random = new Random();
- return random.Next(min, max);
- }
-
-
-
- public string RandomString(int size, bool lowerCase)
- {
- StringBuilder builder = new StringBuilder();
- Random 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();
- }
-
-
- public string RandomPassword(int size = 0)
- {
- StringBuilder builder = new StringBuilder();
- builder.Append(RandomString(4, true));
- builder.Append(RandomNumber(1000, 9999));
- builder.Append(RandomString(2, false));
- return builder.ToString();
- }
- }
Listing 7.
The random string and random password look like Figure 2.
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.
- using System;
- public class RandomStringInArraySample
- {
- public static void Main()
- {
-
- string[] authors = { "Mahesh Chand", "Jeff Prosise", "Dave McCarter", "Allen O'neill",
- "Monica Rathbun", "Henry He", "Raj Kumar", "Mark Prime",
- "Rose Tracey", "Mike Crown" };
-
-
- Random rand = new Random();
-
- int index = rand.Next(authors.Length);
-
-
- Console.WriteLine($"Randomly selected author is {authors[index]}");
-
- Console.ReadKey();
- }
- }
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.
-
- Random random = new Random();
-
- 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.
-
-
- public string RandomString(int size, bool lowerCase)
- {
- StringBuilder builder = new StringBuilder();
- Random 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();
- }
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.
-
- public string RandomPassword(int size = 0)
- {
- StringBuilder builder = new StringBuilder();
- builder.Append(RandomString(4, true));
- builder.Append(RandomNumber(1000, 9999));
- builder.Append(RandomString(2, false));
- return builder.ToString();
- }
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.
- using System;
- using System.Text;
-
- class RandomNumberSample
- {
- static void Main(string[] args)
- {
-
- Random random = new Random();
-
- int num = random.Next();
-
-
- int randomLessThan100 = random.Next(100);
- Console.WriteLine(randomLessThan100);
-
-
- int randomBetween100And500 = random.Next(100, 500);
- Console.WriteLine(randomBetween100And500);
-
-
- RandomNumberGenerator generator = new RandomNumberGenerator();
- int rand = generator.RandomNumber(5, 100);
- Console.WriteLine($"Random number between 5 and 100 is {rand}");
-
- string str = generator.RandomString(10, false);
- Console.WriteLine($"Random string of 10 chars is {str}");
-
- string pass = generator.RandomPassword();
- Console.WriteLine($"Random password {pass}");
-
- Console.ReadKey();
- }
- }
-
- public class RandomNumberGenerator
- {
-
- public int RandomNumber(int min, int max)
- {
- Random random = new Random();
- return random.Next(min, max);
- }
-
-
-
- public string RandomString(int size, bool lowerCase)
- {
- StringBuilder builder = new StringBuilder();
- Random 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();
- }
-
-
- public string RandomPassword(int size = 0)
- {
- StringBuilder builder = new StringBuilder();
- builder.Append(RandomString(4, true));
- builder.Append(RandomNumber(1000, 9999));
- builder.Append(RandomString(2, false));
- return builder.ToString();
- }
- }
Listing 7.
The random string and random password look like Figure 2.
Figure 2.