Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,844 questions

55,671 answers

573 users

How to generate a series of unique HEX colors in C#

1 Answer

0 votes
using System;
using System.Collections.Generic;

class UniqueHexColors
{
    // Convert an integer (0–255) to a two-digit HEX string.
    static string ToHex(int value)
    {
        return value.ToString("X2").ToLower();
    }

    // Generate N unique random HEX colors.
    static string[] GenerateRandomUniqueHexColors(int count)
    {
        var seen = new HashSet<string>();
        var colors = new string[count];
        var rnd = new Random();

        int generated = 0;

        while (generated < count)
        {
            int r = rnd.Next(256);
            int g = rnd.Next(256);
            int b = rnd.Next(256);

            string hex = "#" + ToHex(r) + ToHex(g) + ToHex(b);

            if (seen.Add(hex)) {
                colors[generated] = hex;
                generated++;
            }
        }

        return colors;
    }

    static void Main()
    {
        int n = 12;

        var colors = GenerateRandomUniqueHexColors(n);

        Console.WriteLine("Generated HEX colors:");
        foreach (var c in colors)
        {
            Console.WriteLine(c);
        }
    }
}


/*
run:

Generated HEX colors:
#794077
#991cad
#2d48ef
#73fc9e
#22f7ec
#804d11
#fed5d0
#0f611e
#75bb83
#49641b
#fa6527
#ed1cd0

*/

 



answered 1 day ago by avibootz
...