AvaloniaUI/Avalonia · error · FormatException

Invalid color string: '{s}'.

Error message

Invalid color string: '{s}'.

What it means

Color.Parse(string) throws FormatException when the input cannot be parsed as a color. Accepted formats include known color names and hex strings (#RGB, #RRGGBB, #AARRGGBB, #RRGGBBAA, and optionally rgb()/rgba()-style). This overload explicitly checks for null first (ArgumentNullException) and only throws FormatException for non-null unparseable strings.

Source

Thrown at src/Avalonia.Base/Media/Color.cs:120

        /// <summary>
        /// Parses a color string.
        /// </summary>
        /// <param name="s">The color string.</param>
        /// <returns>The <see cref="Color"/>.</returns>
        public static Color Parse(string s)
        {
            if (s is null)
            {
                throw new ArgumentNullException(nameof(s));
            }

            if (TryParse(s, out Color color))
            {
                return color;
            }

            throw new FormatException($"Invalid color string: '{s}'.");
        }

        /// <summary>
        /// Parses a color string.
        /// </summary>
        /// <param name="s">The color string.</param>
        /// <returns>The <see cref="Color"/>.</returns>
        public static Color Parse(ReadOnlySpan<char> s)
        {
            if (TryParse(s, out Color color))
            {
                return color;
            }

            throw new FormatException($"Invalid color string: '{s.ToString()}'.");
        }

        /// <summary>

View on GitHub (pinned to 11c5427268)

Solutions

  1. Use Color.TryParse(s, out var color) and handle the false return instead of Parse.
  2. Verify the string matches an accepted format: named color, #RGB, #RRGGBB, #AARRGGBB.
  3. Trim whitespace and validate before parsing user/config input.

Example fix

// before
var color = Color.Parse(configValue);

// after
if (!Color.TryParse(configValue?.Trim(), out var color))
    color = Colors.Black; // fallback
Defensive patterns

Strategy: validation

Validate before calling

if (!Color.TryParse(s, out var color))
    color = Colors.Black; // fallback
// now color is guaranteed valid

Try / catch

Color color;
try { color = Color.Parse(s); }
catch (FormatException) { color = Colors.Black; }

Prevention

When it happens

Trigger: Calling Color.Parse(s) where s is a non-null string that is not a recognized color name or valid hex/rgb format. E.g. "orang", "#12", "rgb(a,b,c)".

Common situations: User-supplied or config-file color strings with typos or wrong format. Hardcoded color strings that were edited incorrectly. Interop with another framework's color notation. Trailing whitespace or culture-specific decimal separators.

Related errors


AI-assisted analysis of AvaloniaUI/Avalonia@11c5427268 (2026-08-13). Data as JSON: /api/errors/adb108c3a13b655e. Report an issue: GitHub.