C# Random Number And C# Random String Generator With Code Examples

By Sruthy

By Sruthy

Sruthy, with her 10+ years of experience, is a dynamic professional who seamlessly blends her creative soul with technical prowess. With a Technical Degree in Graphics Design and Communications and a Bachelor’s Degree in Electronics and Communication, she brings a unique combination of artistic flair…

Learn about our editorial policies.
Updated March 7, 2024

Learn How to Generate C# Random Number, Random Alphabet and Random String Containing Special Characters in this Informative C# Tutorial with Code Examples:

There are scenarios where we are required to generate random numbers, alphabets, characters, etc. For achieving this we have Random class available in the System namespace.

The random class allows you to randomly generate an integer value. Using this random class one can generate a different set of numbers/characters. We will discuss this further in this tutorial.

=> Watch Out The Full C# Training Series Here

C# Random Number Generator

How To Generate Random Integer Number In C#?

The random class offers three overload methods to generate integers based on the parameter provided by the user. Let’s have a look at all three methods.

Using C# Random.Next()

Next contains three overloads:

Next() Without Argument

The first overload for the Random.Next() doesn’t require any argument. It returns a non-negative integer value.

Example:

class Program
      {
public static void Main(string[] args)
               {
                        Random ran = new Random();
int a = ran.Next();

Console.WriteLine("The random number generated is: {0}", a);

Console.ReadLine();
                }
        }

The output of the above program will be any non-negative random value:

Output

The random number generated is: 157909285

Next() With One Argument

Next overload for the Random.Next() accepts one argument. The argument provided specifies the maximum value that can be generated by the method. The max value should be either greater than or equal to zero. It returns a non-negative integer with max value as the argument provided by the user.

Example:

 
class Program
       {
public static void Main(string[] args)
          {
                         Random ran = new Random();
int a = ran.Next(1000);
            
Console.WriteLine("The random number generated by Random.Next(argument) is: {0}", a);
            
Console.ReadLine();
                }
    }

The output of the above program will generate an integer greater than zero and less than the maximum value entered i.e. 1000.

Output

The random number generated by Random.Next(argument) is: 574

Next() With Two Arguments

Random class is used to simulate a random event. To generate a random character, we use Next(). The Next() accepts two arguments, the first one is the minimum and inclusive value allowed for the random generator.

The second argument accepts the maximum exclusive value. A maximum exclusive value means that the value passed in the second argument will never be generated. The generated value will always be less than the max value.

Let’s have a look at a simple program :

class Program
      {
public static void Main(string[] args)
               {
                        Random ran = new Random();
int a = ran.Next(10, 1000);
            
Console.WriteLine("The random number generated by Random.Next(minVal, maxVal) is: {0}", a);
            
Console.ReadLine();
                }
         }

The output of the above program will produce a value between the given range i.e. between 10 and 1000 where the minimum value i.e. 10 is inclusive.

Output

The random number generated by Random.Next(minVal, maxVal) is: 137

In the above example, we discussed how to generate a random integer. But in case you want to generate a random alphabet, we will be using the Random class.

How To Generate Random Alphabets?

We can generate a random alphabet by using the random class. Although Random class only returns an integer, we can use that to generate random alphabets.

The easiest way to do that is to combine the “ElementAt” method with the Random.Next() to point out the position of a random alphabet from the series of alphabets.

Example:

class Program
       {
public static void Main(string[] args)
                {
                        Random ran = new Random();
            
                        String b = "abcdefghijklmnopqrstuvwxyz";
           
                        int length = 6;
            
                       String random = "";
            
                     for(int i =0; i<length; i++)
                     {
                             int a = ran.Next(26);
                             random = random + b.ElementAt(a);
                     }
            
                Console.WriteLine("The random alphabet generated is: {0}", random);
            
                Console.ReadLine();
                }
        }

The output of the above program will be:

The random alphabet generated is: icysjd

Code Explanation

Similar to our previous examples, here we created a Random object. Then we stored all the alphabets in a string i.e. String b. We defined a variable called “length” of integer type which will denote the number of characters required in a randomly generated string.

We initialized empty string random, where we will store our alphabets. Then we wrote a for loop. Inside the for loop we used Random.Next() to generate a random number less than 26 because the number of alphabets we stored in the String b is 26. You can also other numbers depending on the requirement.

Hence, the int a will have a random number generated during each loop cycle, then that number will be used as a position indicator to get the character that position using ElementAt(). This will give a random character every time when the loop runs.

Then we will append the characters together on each loop cycle and we will get the required string with the given length.

Generate Random Alphanumeric String With Special Characters

To generate an alphanumeric string with a special character, the simplest way is similar to the one we discussed in the above example. We will need to add the numerals and special characters to the given variable from which it can pick up random values.

But as the program will pick-up characters randomly, there may be a chance that it doesn’t pick anything. If your program output requires to have a mandatory special character then it’s a little bit tricky. Let’s discuss a program to generate alphanumeric text with mandatory special characters.

The following program will generate an 8-digit random alphanumeric output with the last two digits as special characters.

    
class Program
       {
public static void Main(string[] args)
                {
                         Random ran = new Random();
                    
                         String b = "abcdefghijklmnopqrstuvwxyz0123456789";
                         String sc = "!@#$%^&*~";
            
                         int length = 6;
           
                         String random = "";
            
for(int i =0; i<length; i++)
                  {
                            int a = ran.Next(b.Length); //string.Lenght gets the size of string
                            random = random + b.ElementAt(a);
                   }
for(int j =0; j<2; j++)
                   {
                            int sz = ran.Next(sc.Length); 
                            random = random + sc.ElementAt(sz);
                       }
            
Console.WriteLine("The random alphabet generated is: {0}", random);
            
Console.ReadLine();
                }
        }

The output of the above program will be:

The random alphabet generated is: 718mzl~^

Code Explanation

In the above program, we used the same logic that we followed in the last example. Along with the variable that contains alphanumeric characters we also created another string variable with special characters.

Then we ran a for loop to generate a 6-digit alphanumeric character, similar to the one we did in our previous problem. We also wrote another for loop that generated 2 random special characters from the given string. The special characters generated were appended with the random string that we declared at the start of the program.

This produced an 8 digit output with 6 alphanumeric characters and the last two special characters. You do a little tweaking of your own to generate strings as per your own requirement.

Consolidated Program

class Program
       {
public static void Main(string[] args)
               {
                        Random ran = new Random();

//Output for Random.Next()
Console.WriteLine("The random number generated by Random.Next() is: {0}", ran.Next());
//Output for Random.Next(argument) with max value limit
Console.WriteLine("The random number generated by Random.Next(argument) is: {0}", ran.Next(10));
//Output for Random.Next(argument1, argument2) with max and min value limit
Console.WriteLine("The random number generated by Random.Next(argument1, argument2) is: {0}", ran.Next(10, 100));
            

                         String b = "abcdefghijklmnopqrstuvwxyz0123456789";
                         String sc = "!@#$%^&*~";
            
int length = 6;
            
                         String random = "";
            
for(int i =0; i<length; i++)
                    {
int a = ran.Next(b.Length); //string.Lenght gets the size of string
                              random = random + b.ElementAt(a);
                     }

for(int j =0; j<2; j++)
                     {
int sz = ran.Next(sc.Length); 
                              random = random + sc.ElementAt(sz);
                      }
            
Console.WriteLine("The random alphabet generated is: {0}", random);
            
Console.ReadLine();
                }
    }

The output of the program

The random number generated by Random.Next() is: 1497664941
The random number generated by Random.Next(argument) is: 8
The random number generated by Random.Next(argument1, argument2) is: 92
The random alphabet generated is: b173gq#*

Conclusion

The Random class is present inside the System namespace in C#.

It has three overload methods, that allow the user to generate a random integer based on the values provided through the argument. The random class is not the perfect way to generate a random value but is the simplest way to achieve it.

=> Read Through The C# Guide For Beginners Here

Was this helpful?

Thanks for your feedback!

Leave a Comment