Question

Generate Random Alphanumeric Strings in C#

csharp.netrandom

Question

How can I generate a random 8-character alphanumeric string in C#?

I want to create a string that is exactly 8 characters long, where each character is chosen randomly from letters and numbers.

Short Answer

By the end of this page, you will understand how to generate random alphanumeric strings in C#, how to choose characters from a valid character set, and when to use a basic random generator versus a cryptographically secure one.

Concept

Generating a random alphanumeric string means building a string one character at a time from a set of allowed characters, such as:

ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789

The main idea is simple:

  1. Define the allowed characters.
  2. Randomly pick one character at a time from that set.
  3. Repeat until the string reaches the required length.

In C#, this is commonly done with either:

  • Random for general-purpose, non-security-critical use
  • RandomNumberGenerator for secure tokens, codes, and identifiers

This concept matters because random strings are used in many real programs, including:

  • temporary file names
  • invitation codes
  • test data
  • one-time codes
  • non-guessable identifiers

A key detail is that not all random generators are equally suitable. If the string is used for security, such as password reset links or access tokens, Random is not enough. In those cases, use RandomNumberGenerator.

Mental Model

Think of the allowed characters as letters and numbers written on slips of paper inside a bag.

To build the final string:

  • shake the bag
  • pull out one slip
  • write it down
  • put it back
  • repeat until you have 8 characters

The bag is your character set. The repeated picking is your loop. The final written result is your random string.

If the bag is shaken poorly, patterns may appear. That is why secure random generators are important when unpredictability matters.

Take Quiz

Syntax and Examples

Basic approach with Random

using System;
using System.Text;

class Program
{
    static string GenerateRandomString(int length)
    {
        const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuilder result = new StringBuilder(length);

        for (int i = 0; i < length; i++)
        {
            int index = random.Next(chars.Length);
            result.Append(chars[index]);
        }

        return result.ToString();
    }

    static void Main()
    {
        string value = GenerateRandomString(8);
        Console.WriteLine(value);
    }
}

This code:

  • defines all allowed letters and digits in chars
  • uses random.Next(chars.Length) to pick a valid index
  • appends one random character per loop iteration
  • returns the completed string

Secure approach with RandomNumberGenerator

using System;
using System.Security.Cryptography;
using System.Text;

class Program
{
    static string GenerateSecureRandomString(int length)
    {
        const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        StringBuilder result = new StringBuilder(length);

        for (int i = 0; i < length; i++)
        {
            int index = RandomNumberGenerator.GetInt32(chars.Length);
            result.Append(chars[index]);
        }

        return result.ToString();
    }

    static void Main()
    {
        string value = GenerateSecureRandomString(8);
        Console.WriteLine(value);
    }
}

This version is better when the string should be hard to predict.

Example output

A7kP2xQ9
m3Tz8Lw1

Each run produces a different 8-character alphanumeric string.

Step by Step Execution

Consider this example:

const string chars = "ABC123";
int length = 4;

Suppose the random indexes chosen are:

2, 0, 4, 5

Now walk through it:

  1. chars is "ABC123"

    • index 0 = A
    • index 1 = B
    • index 2 = C
    • index 3 = 1
    • index 4 = 2
    • index 5 = 3
  2. First random index is 2

    • pick C
    • result becomes "C"
  3. Second random index is 0

    • pick A
    • result becomes "CA"
  4. Third random index is 4

    • pick 2
    • result becomes "CA2"
  5. Fourth random index is 5

    • pick 3
    • result becomes "CA23"

Final output:

CA23

This is exactly how the full version works. The only difference is that the real character set is much larger and the length is usually 8 or more.

Real World Use Cases

Random alphanumeric strings are useful in many situations:

  • Invite codes: generate short codes for user referrals or private signups
  • Temporary passwords: create initial login credentials
  • Verification codes: send short codes in emails or messages
  • Test data generation: create random sample usernames or IDs during development
  • File or batch identifiers: label exported reports or uploaded documents
  • Order references: generate human-readable IDs that include letters and numbers

Example: a web application might create an 8-character code for a user invitation:

string inviteCode = GenerateSecureRandomString(8);

That code can then be stored in a database and shared with a user.

Take Quiz

Real Codebase Usage

In real projects, developers usually wrap this logic inside a reusable method or service rather than writing it inline every time.

Common patterns include:

Validation

Check that the requested length is valid:

if (length <= 0)
    throw new ArgumentException("Length must be greater than zero.");

This is a guard clause. It stops invalid input early.

Reusable utility method

A helper method keeps the code clean:

string code = RandomHelper.GenerateSecureRandomString(8);

Configuration

The allowed character set is often customized based on business rules:

  • letters only
  • digits only
  • uppercase only
  • no confusing characters like O and 0, or I and 1

Example:

const string chars = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";

Error prevention

Developers avoid creating many Random instances in a short time because repeated seeding can cause duplicate-looking results.

Security-sensitive usage

For reset tokens, API keys, and authentication-related values, teams prefer RandomNumberGenerator over Random.

Common Mistakes

1. Using Random for security-sensitive values

Broken example:

Random random = new Random();
string token = chars[random.Next(chars.Length)].ToString();

This is fine for simple demos or test data, but not for secure tokens.

Use this instead:

int index = RandomNumberGenerator.GetInt32(chars.Length);

2. Creating new Random() too often

Broken example:

for (int i = 0; i < 5; i++)
{
    Random random = new Random();
    Console.WriteLine(chars[random.Next(chars.Length)]);
}

Creating many Random objects quickly can produce repeated patterns.

Better approach:

Random random = new Random();
for (int i = 0; i < 5; i++)
{
    Console.WriteLine(chars[random.Next(chars.Length)]);
}

3. Using an invalid index range

Broken example:

int index = random.Next(chars.Length + 1);
result.Append(chars[index]);

This can cause an index-out-of-range error.

Correct:

int index = random.Next(chars.Length);

4. Forgetting to control the string length

Broken example:

string result = "";
while (true)
{
    result += chars[random.Next(chars.Length)];
}

This never stops.

Use a loop with a clear limit.

5. Building strings inefficiently in a loop

This works, but can be less efficient for larger strings:

string result = "";
for (int i = 0; i < length; i++)
{
    result += chars[random.Next(chars.Length)];
}

Prefer StringBuilder when repeatedly appending characters.

Comparisons

OptionBest forSecure?Notes
RandomSimple apps, demos, test dataNoEasy to use, but predictable for security use cases
RandomNumberGeneratorTokens, codes, security-sensitive valuesYesBetter when unpredictability matters
Hardcoded stringFixed identifiersNoNot random at all

string concatenation vs StringBuilder

ApproachUse caseNotes
result += charVery small scriptsSimple, but less efficient in loops
StringBuilderRepeated appendingPreferred for generating strings in loops

Full character set vs restricted character set

Character setExampleWhy use it
Full alphanumericA-Z a-z 0-9Maximum variety
Uppercase + digitsA-Z 0-9Easier to read and type
No ambiguous charactersABCDEFGHJKLMNPQRSTUVWXYZ23456789Avoids confusion between O/0 and I/1
Take Quiz

Cheat Sheet

const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

Generate a simple random string

Random random = new Random();
StringBuilder result = new StringBuilder(length);

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

string finalValue = result.ToString();

Generate a secure random string

for (int i = 0; i < length; i++)
{
    result.Append(chars[RandomNumberGenerator.GetInt32(chars.Length)]);
}

Rules to remember

  • Use a defined character set.
  • Use random.Next(chars.Length) for valid indexes.
  • Use StringBuilder for repeated appends.
  • Use RandomNumberGenerator for secure values.
  • Validate that length > 0.

Common edge cases

  • length <= 0 should usually throw an exception.
  • Recreating Random many times can lead to repeated output patterns.
  • If users must type the code manually, remove confusing characters like 0, O, 1, and I.

FAQ

How do I generate a random 8-character string in C#?

Create a character set, loop 8 times, pick a random character each time, and append it to a result string.

Should I use Random or RandomNumberGenerator in C#?

Use Random for non-sensitive tasks like sample data. Use RandomNumberGenerator for tokens, verification codes, and security-related values.

How can I include only letters and numbers?

Define the allowed characters yourself, for example:

const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

How do I make the string uppercase only?

Use a smaller character set:

const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

Why do I sometimes get repeated random values?

If you create new Random() repeatedly in a short time, the generated values may look similar. Reuse one instance or use RandomNumberGenerator.

Can I avoid confusing characters like O and 0?

Yes. Use a custom character set such as:

const string chars = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
Take Quiz

Mini Project

Description

Build a small C# utility that generates invite codes for a registration system. Each invite code should be 8 characters long and contain only uppercase letters and digits, making it easy to read and share.

Goal

Create a reusable method that generates secure 8-character invite codes and prints several examples.

Requirements

  • Create a method that accepts the desired code length.
  • Use only uppercase letters and digits in the generated code.
  • Use a secure random generator.
  • Validate that the length is greater than zero.
  • Print at least 5 generated codes.
Take Quiz

Keep learning

Related questions

View more