AvaloniaUI/Avalonia · error · InvalidCastException

IterationCount can't be a negative number.

Error message

IterationCount can't be a negative number.

What it means

Thrown by IterationCount.Parse when the input string (uppercased, trimmed) starts with '-'. IterationCount stores a ulong, which cannot be negative, so a leading minus sign is rejected up front rather than letting ulong.Parse fail with a less clear message.

Source

Thrown at src/Avalonia.Base/Animation/IterationCount.cs:165

        }

        /// <summary>
        /// Parses a string to return a <see cref="IterationCount"/>.
        /// </summary>
        /// <param name="s">The string.</param>
        /// <returns>The <see cref="IterationCount"/>.</returns>
        public static IterationCount Parse(string s)
        {
            s = s.ToUpperInvariant().Trim();

            if (s.EndsWith("INFINITE"))
            {
                return Infinite;
            }
            else
            {
                if (s.StartsWith("-"))
                    throw new InvalidCastException("IterationCount can't be a negative number.");

                var value = ulong.Parse(s, CultureInfo.InvariantCulture);

                return new IterationCount(value);
            }
        }
    }
}

View on GitHub (pinned to 11c5427268)

Solutions

  1. Validate that the input is non-negative before parsing.
  2. Map negative/'forever' intents to the 'Infinite' token instead of a negative number.
  3. Use ulong.TryParse and reject <= 0 semantics explicitly in your UI.

Example fix

// before
var ic = IterationCount.Parse("-1");

// after
var ic = IterationCount.Parse("Infinite");
// or
var ic = IterationCount.Infinite;
Defensive patterns

Strategy: validation

Validate before calling

if (s.TrimStart().StartsWith('-'))
    throw new InvalidCastException("IterationCount cannot be negative; use 'Infinite'.");

Type guard

static bool IsNonNegativeIterationString(string s) => !s.TrimStart().StartsWith('-');

Prevention

When it happens

Trigger: Calling IterationCount.Parse("-1") or any string beginning with '-' (and not matching 'Infinite').

Common situations: User/UX input of a negative repeat count; sign error in computed count; sentinel value (-1) passed unparsed.

Related errors


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