C# programming
string conversion
color manipulation
code example
software development

Convert string to Color in C

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Converting a string to a color in C# sounds simple until you notice that color strings can come in several formats. You might receive a named color such as Red, a web hex value such as #FF0000, or an ARGB-style value that needs custom parsing.

Choose the API Based on the Input Format

In C#, there is no single universal parser that always means the same thing across every UI stack. The most common choices are:

  • 'ColorTranslator.FromHtml for HTML-style color strings'
  • 'Color.FromName for known color names'
  • 'ColorConverter for more flexible component-model conversion'

If you are using System.Drawing.Color, ColorTranslator.FromHtml is often the easiest answer for web-style colors.

Parsing Hex and Named Colors

Here is a practical helper for System.Drawing.Color:

csharp
1using System;
2using System.Drawing;
3
4public static class ColorParser
5{
6    public static Color Parse(string input)
7    {
8        if (string.IsNullOrWhiteSpace(input))
9            throw new ArgumentException("Color string is empty.", nameof(input));
10
11        input = input.Trim();
12
13        if (input.StartsWith("#"))
14        {
15            return ColorTranslator.FromHtml(input);
16        }
17
18        Color named = Color.FromName(input);
19        if (named.IsKnownColor || named.IsNamedColor)
20        {
21            return named;
22        }
23
24        throw new ArgumentException($"Unsupported color value: {input}", nameof(input));
25    }
26}

Usage:

csharp
1Color c1 = ColorParser.Parse("#00FF00");
2Color c2 = ColorParser.Parse("Red");
3
4Console.WriteLine(c1);
5Console.WriteLine(c2);

This handles the two most common formats cleanly.

Supporting Alpha Values

One detail that surprises people is alpha handling. ColorTranslator.FromHtml works well for standard HTML-style colors, but if your input includes a custom #AARRGGBB format, you may want to parse it yourself.

Example:

csharp
1using System;
2using System.Drawing;
3using System.Globalization;
4
5public static Color ParseArgb(string input)
6{
7    if (input is null || !input.StartsWith("#") || input.Length != 9)
8        throw new ArgumentException("Expected #AARRGGBB format.", nameof(input));
9
10    int a = int.Parse(input.Substring(1, 2), NumberStyles.HexNumber);
11    int r = int.Parse(input.Substring(3, 2), NumberStyles.HexNumber);
12    int g = int.Parse(input.Substring(5, 2), NumberStyles.HexNumber);
13    int b = int.Parse(input.Substring(7, 2), NumberStyles.HexNumber);
14
15    return Color.FromArgb(a, r, g, b);
16}

This is useful when the incoming format is controlled by your own application or API.

ColorConverter as a Flexible Option

ColorConverter can also parse many textual representations:

csharp
1using System;
2using System.ComponentModel;
3using System.Drawing;
4
5TypeConverter converter = TypeDescriptor.GetConverter(typeof(Color));
6Color color = (Color)converter.ConvertFromString("Blue");

This is convenient in configuration-heavy code, but for a narrow known input format, a dedicated parser is often clearer.

Be Careful About Framework Differences

If you are writing WPF code, you may be using System.Windows.Media.Color instead of System.Drawing.Color. The APIs are similar in spirit but not interchangeable.

That means the correct parser depends on which Color type your app actually uses. Mixing them is a common source of confusion in older desktop codebases.

Error Handling Strategy

A good parser should fail explicitly on unsupported input rather than silently returning black or transparent by accident. Color parsing bugs are easy to miss because the UI still renders something.

In reusable code, prefer one of these patterns:

  • throw ArgumentException for invalid input
  • provide a TryParse-style method that returns bool
  • log and fall back only when the UI genuinely has a safe default

Common Pitfalls

The biggest mistake is assuming Color.FromName validates all input. Unknown names usually return a color object that looks harmless but does not represent a real known color in the way most developers expect.

Another issue is ignoring alpha format. Some inputs use #RRGGBB, while others use #AARRGGBB, and those are not interchangeable.

Developers also often mix System.Drawing.Color with WPF color types and then wonder why converter code does not compile or behaves differently.

Finally, do not silently swallow bad color strings. Invalid UI data should be easy to diagnose.

Summary

  • Pick the parsing API based on the expected input format.
  • Use ColorTranslator.FromHtml for common web-style hex values.
  • Use Color.FromName or ColorConverter for named colors when appropriate.
  • Parse alpha-inclusive formats explicitly if your input uses them.
  • Be clear about whether your app uses System.Drawing.Color or a different color type.

Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.