DEV Community

Cover image for Generate 6 or 8 digit alpha numeric code using best performance in C#
Neer S
Neer S

Posted on

Generate 6 or 8 digit alpha numeric code using best performance in C#

Generating a 6 or 8-digit alphanumeric code in C# involves creating a string consisting of random letters and numbers. Here is a C# example using best practices and focusing on performance:

Use a StringBuilder for efficient string concatenation.
Use RandomNumberGenerator for cryptographic security.

Cache the character array to avoid creating it repeatedly.

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

public class AlphaNumericCodeGenerator
{
    private static readonly char[] chars =
        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".ToCharArray();

    public static string GenerateCode(int length)
    {
        if (length != 6 && length != 8)
        {
            throw new ArgumentException("Code length must be either 6 or 8.", nameof(length));
        }

        using (var rng = RandomNumberGenerator.Create())
        {
            var bytes = new byte[length];
            rng.GetBytes(bytes);

            var result = new StringBuilder(length);
            foreach (var byteValue in bytes)
            {
                result.Append(chars[byteValue % chars.Length]);
            }

            return result.ToString();
        }
    }

    public static void Main()
    {
        string code6 = GenerateCode(6);
        Console.WriteLine($"6-digit code: {code6}");

        string code8 = GenerateCode(8);
        Console.WriteLine($"8-digit code: {code8}");
    }
}
Enter fullscreen mode Exit fullscreen mode

Explanation:

Character Array: A cached array of characters (both upper and lower case letters and digits) to avoid creating it repeatedly.

Random Number Generator: RandomNumberGenerator is used for better randomness and security compared to Random.

StringBuilder: Used for efficient string concatenation.
Argument Validation: Ensures the length is either 6 or 8.

Random Bytes: Generates random bytes and maps each byte to a character in the chars array.

Modulo Operation: Maps each byte to a valid index in the chars array.

This code ensures the generated string is both secure and efficient.

Warp.dev image

The best coding agent. Backed by benchmarks.

Warp outperforms every other coding agent on the market, and gives you full control over which model you use. Get started now for free, or upgrade and unlock 2.5x AI credits on Warp's paid plans.

Download Warp

Top comments (0)

Feature flag article image

Create a feature flag in your IDE in 5 minutes with LaunchDarkly’s MCP server ⏰

How to create, evaluate, and modify flags from within your IDE or AI client using natural language with LaunchDarkly's new MCP server. Follow along with this tutorial for step by step instructions.

Read full post

👋 Kindness is contagious

Take a moment to explore this thoughtful article, beloved by the supportive DEV Community. Coders of every background are invited to share and elevate our collective know-how.

A heartfelt "thank you" can brighten someone's day—leave your appreciation below!

On DEV, sharing knowledge smooths our journey and tightens our community bonds. Enjoyed this? A quick thank you to the author is hugely appreciated.

Okay