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.

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay