How to Generate Random Generator for Numbers and String | C# Examples

This is a Short tutorial on Generating Random Numbers and Strings in c#.

Random values are unique values generated for each execution. Value can be Numbers or alphanumeric Strings.

C# Random Number Generator Example

C# has a Random class, Next() method to generate Random Numbers. It contains three variations for Next() method Firstly, Using Random.next() generates random number Secondly, Random.Next(seed), Generates Random always less than Seed. Thirdly, Random.next(min, max) to generates a Random number between minimum and maximum of numbers.

Syntax:

// Random Number
Random.Next();
// Generates Random Number between min and max
Random.Next(lower,higher);

Here is an Example

using System;

public class Program
{
	public static void Main()
	{
		Random random = new Random();
		int randomNumber = random.Next();
		Console.WriteLine(randomNumber);

	}
}

Generate a Random Number between the minimum and maximum numbers

The below program generates Random numbers between 1 and 10 always.

using System;

public class Program
{
	public static void Main()
	{
		Random random = new Random();
		int randomNumber = random.Next(1,10);
		Console.WriteLine(randomNumber);

	}
}

C# Random Alphanumeric String Generator Example

This example generates a Random Alpha numeric Character String with any length.

  • Create a Reusable function of a given length
  • Define the range of characters to include in random String
  • Import System.Text to create a StringBuilder.
  • Generates a Random Number using the Random class.
  • Get the character for a given random as an index
  • Append the character to StringBuilder.
  • Repeat the above 3 steps for a given size of
  • Finally, Return the random String.

Here is an example

using System;
using System.Text;

public class Program {
  public static void Main() {

    Console.WriteLine(RandomString(10));

  }
  public static string RandomString(int length = 10) {
    var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    var randomString = new StringBuilder();
    var random = new Random();

    for (int i = 0; i < length; i++)
      randomString.Append(chars[random.Next(chars.Length)]);

    return randomString.ToString();
  }

}