How
to Generate a Random String in C#?
How
to Generate a Random 10 digit number in C#?
Random
represents a pseudo-random number generator, which is a device that produces a sequence of numbers that meet certain statistical requirements for randomness.
The Random
() constructor uses the system clock
to provide a seed value. This is the most common way of instantiating the
random number generator.
Random Char should be a method because it returns
a different result each time - this is just a convention that we usually follow
in ASP.Net C#.
Example
1 for Random string generation
/// <summary>
///
Random String Generation with any specified length
/// </summary>
public static string
GenerateRandomString(int length)
{
Random random = new
Random();
StringBuilder strResult = new
StringBuilder(length);
string
chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
for
(int i = 0; i < length; i++)
strResult.Append(chars[random.Next(chars.Length)]);
return
strResult.ToString();
}
Example
2 for Random number generation
/// <summary>
///
Create Random Digits with any specified length
/// </summary>
public string
RandomDigits(int length)
{
Random random = new
Random();
string
result = string.Empty;
for
(int i = 0; i < length; i++)
result = String.Concat(result,
random.Next(10).ToString());
return
result;
}