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.

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs