C# – Randomly generated hexadecimal number in C#

c++hexrandom

How can I generate a random hexadecimal number with a length of my choice using C#?

Best Solution

static Random random = new Random();
public static string GetRandomHexNumber(int digits)
{
    byte[] buffer = new byte[digits / 2];
    random.NextBytes(buffer);
    string result = String.Concat(buffer.Select(x => x.ToString("X2")).ToArray());
    if (digits % 2 == 0)
        return result;
    return result + random.Next(16).ToString("X");
}