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:
- Define the allowed characters.
- Randomly pick one character at a time from that set.
- Repeat until the string reaches the required length.
In C#, this is commonly done with either:
Randomfor general-purpose, non-security-critical useRandomNumberGeneratorfor 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.
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
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:
-
charsis"ABC123"- index
0=A - index
1=B - index
2=C - index
3=1 - index
4=2 - index
5=3
- index
-
First random index is
2
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.
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
Oand0, orIand1
Example:
const string chars = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
Error prevention
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:
Comparisons
| Option | Best for | Secure? | Notes |
|---|---|---|---|
Random | Simple apps, demos, test data | No | Easy to use, but predictable for security use cases |
RandomNumberGenerator | Tokens, codes, security-sensitive values | Yes | Better when unpredictability matters |
| Hardcoded string | Fixed identifiers | No | Not random at all |
string concatenation vs StringBuilder
| Approach | Use case | Notes |
|---|---|---|
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
StringBuilderfor repeated appends. - Use
RandomNumberGeneratorfor secure values. - Validate that
length > 0.
Common edge cases
length <= 0should usually throw an exception.- Recreating many times can lead to repeated output patterns.
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 ?
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.
Keep learning
Related questions
AddTransient vs AddScoped vs AddSingleton in ASP.NET Core Dependency Injection
Learn the differences between AddTransient, AddScoped, and AddSingleton in ASP.NET Core DI with examples and practical usage.
C# Type Checking Explained: typeof vs GetType() vs is
Learn when to use typeof, GetType(), and is in C#. Understand exact type checks, inheritance, and safe type testing clearly.
C# Version Numbers Explained: C# vs .NET Framework and Why “C# 3.5” Is Incorrect
Learn the correct C# version numbers, how they map to .NET releases, and why terms like C# 3.5 are inaccurate and confusing.