C# Random class provides functionality to generate random numbers in C#. The Random class can also generate other data types, including strings. In this code example, learn how to create a random number in C#.
Random class constructors have two overloaded forms. It takes either no value, or it takes a seed value. The Random class provides Random.Next(), Random.NextBytes(), and Random.NextDouble() methods. The Random.Next() method returns a random number, Random.NextBytes() returns an array of bytes filled with random numbers and Random.NextDouble() returns a random number between 0.0 and 1.0.
The Random.Next() method has three overloaded forms and allows you to set the minimum and maximum range of the random number.
The following code returns a random number.
The following code returns a random number less than 1000.
The following code returns a random number between the min and the max range.
You can even combine the two methods - RandomNumber and RandomString to generate a combination of random strings and numbers.
The following code generates a password of length 10 with the first 4 letters lowercase, the next 4 letters numbers, and the last 2 letters as uppercase.
Here is the complete code written in .NET Core 5.0. using System;
using System.T
The output from the above code is shown in figure 1.
![]()
Figure 1. Console Output
Summary
This article and code example taught you how to generate random numbers and random strings in C#.