Mohanapriya R Mohanapriya R
Updated date Jul 30, 2024
In this article, we will learn how to convert hexadecimal color codes to color representations in C#.

Converting Hexadecimal to Color in C#

To convert hexadecimal color codes to color representations in C#, we can use the Color struct provided by the .NET framework. The Color struct represents a color in terms of its RGB components.

Here's a simple C# program that shows how to convert a hexadecimal color code to a Color object:

using System;
using System.Drawing;

class Program
{
    static void Main(string[] args)
    {
        string hexCode = "#FFA500"; // Hexadecimal color code for orange
        Color color = ColorTranslator.FromHtml(hexCode);

        Console.WriteLine($"Hexadecimal: {hexCode}");
        Console.WriteLine($"Color: {color}");

        // Additional properties of Color object
        Console.WriteLine($"Red: {color.R}");
        Console.WriteLine($"Green: {color.G}");
        Console.WriteLine($"Blue: {color.B}");
    }
}

We have defined a hexadecimal color code (#FFA500 for orange) and then use ColorTranslator.FromHtml() method to convert it to a Color object. 

Output:

Hexadecimal: #FFA500
Color: Color [A=255, R=255, G=165, B=0]
Red: 255
Green: 165
Blue: 0

Comments (0)

There are no comments. Be the first to comment!!!