AvaloniaUI/Avalonia · error · FormatException
Invalid color string: '{s.ToString()}'.
Error message
Invalid color string: '{s.ToString()}'. What it means
The ReadOnlySpan<char> overload of Color.Parse throws the same FormatException as the string overload, but for span inputs. It exists for performance-sensitive parsing paths (e.g. XAML/JSON parsers) that avoid allocating a string. The error message interpolates s.ToString() so the offending input is visible.
Source
Thrown at src/Avalonia.Base/Media/Color.cs:135
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>
/// Parses a color string.
/// </summary>
/// <param name="s">The color string.</param>
/// <param name="color">The parsed color</param>
/// <returns>The status of the operation.</returns>
public static bool TryParse(string? s, out Color color)
{
color = default;
if (string.IsNullOrEmpty(s))
{
return false;
}
if (s[0] == '#' &&View on GitHub (pinned to 11c5427268)
Solutions
- Use Color.TryParse(ReadOnlySpan<char>, out Color) to avoid the throw on bad input.
- Validate the span content matches a known color/hex format before calling Parse.
- Ensure upstream tokenization produces a clean color token.
Example fix
// before
var color = Color.Parse(tokenSpan);
// after
if (!Color.TryParse(tokenSpan, out var color))
color = Colors.Black; Defensive patterns
Strategy: validation
Validate before calling
if (!Color.TryParse(spanInput, out var color))
color = Colors.Black; Try / catch
Color color;
try { color = Color.Parse(spanInput); }
catch (FormatException) { color = Colors.Black; } Prevention
- Use the span-based TryParse overload to avoid both allocations and exceptions.
- Ensure upstream tokenizers produce clean color tokens.
- Handle parse failures gracefully in high-throughput parsing paths.
When it happens
Trigger: Calling Color.Parse(ReadOnlySpan<char> s) where the span content is not a valid color. Often reached from internal XAML/markup parsers or when slicing a larger buffer.
Common situations: Internal parser feeding a malformed token. A XAML color attribute with a typo. Slicing a buffer incorrectly leaving non-color characters.
Related errors
- Invalid brush string: '{s}'.
- Invalid color string: '{s}'.
- Unknown CacheMode: {s}
- Unable to parse effect: {s}
- Specified family is not supported.
AI-assisted analysis of AvaloniaUI/Avalonia@11c5427268 (2026-08-13).
Data as JSON: /api/errors/b498ebb292eb5f30.
Report an issue: GitHub.