c sharp

How to Generate Random Numbers and Random String in C Sharp

Generating random numbers and strings in C# can be useful for many applications, such as generating unique IDs, testing algorithms, or creating random data for simulation purposes. This article is all about demonstrating different ways to generate random numbers and strings in C#.

How to generate Random Numbers in C#

In C# Random class provides a convenient method for generating random numbers. The Next() function generates a random integer within a specified range, and the NextDouble() function generates a  double-precision floating-point number randomly between 0.0 and 1.0, here is an example that demonstrate the use of Random class to generate a random integer within a declared range:

using System;

namespace RandomNumber
{
    class Program
    {
        static void Main(string[] args)
        {
            // Creating Random class
            Random random = new Random();

            // Generating a random integer from 1 to 100
            int random_number = random.Next(1, 100);

            // Displaying the generated random number
            Console.WriteLine("The random number is: " + random_number);
        }
    }
}

In this example, a new instance of the Random class is created, and a random integer between 1 and 100 is generated using the Next() function. The generated random integer is then displayed on the console using the Console.WriteLine().

Output

Here is some brief explanation for the code:

1: First, we include the system namespace, which contains the Random class that we will use to generate random numbers. Next, we create an instance of the Random class and store it in a variable named random.

2: We then generate a random number between 1 and 100 using the Next() function of the Random class, and store it in a variable named random_number. The Next() function generates a random number between two specified values, inclusive of the minimum value and exclusive of the maximum value.

3: Finally, we write the generated random number to the console using the Console.WriteLine().

How to Generate Random Strings in C#

Generating random strings in C# can be useful for generating random passwords, security codes, or unique identifiers. The following example demonstrates how to generate a random string using the Random class:

using System;

namespace RandomStringExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Creating a new Random class
            Random random_number = new Random();

            // Defining character set
            string setOfCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

            // Defining random string length
            int length = 10;

            // Generate the random string
            string randomString = "";
            for (int i = 0; i < length; i++)
            {
                int index = random_number.Next(0, setOfCharacters.Length - 1);
                randomString += setOfCharacters[index];
            }

            // Displaying the random generated string

            Console.WriteLine("Random string: " + randomString);
        }
    }
}

In this example, a new instance of the Random class is created, and a string of characters is defined using the setOfcharacters string variable. The length of the random string is specified using the length variable.

A for loop is then used to generate the random string by selecting a random character from the steOfcharacters string and concatenating it to the randomString string. The generated random string is then displayed on the console using the Console.WriteLine() method.

Output

Here is some brief explanation of the code we have used to generate random strings:

1: First, we include the system namespace, which contains the Random class that we will use to generate random characters.

2: Next, we declare a variable length to store the length of the random string that we want to generate, and a string variable characters to store the set of characters that we want to use to generate the string.

3: Next we created an instance of the Random class and store it in a variable named random and afterwards create an array of characters randomString of the specified length.

4: Now through the for loop, we use the random.Next() to generate a random index into the characters string, and assign the corresponding character to the randomString array at the current iteration. The random.Next() function generates a random number between 0 (inclusive) and the length of the characters string (exclusive).

5: Finally, we write the generated random string to the console using the Console.WriteLine().

Conclusion

Generating random numbers and strings in C# is a straightforward process using the System.Random class. Whether you need to generate random data for testing purposes, or for generating unique identifiers, the System.Random class provides a simple and convenient solution.

About the author

Aaliyan Javaid

I am an electrical engineer and a technical blogger. My keen interest in embedded systems has led me to write and share my knowledge about them.