tui-cs/Terminal.Gui · error · ArgumentOutOfRangeException

SelectedColor must be between 0 and 15.

Error message

SelectedColor must be between 0 and 15.

What it means

ColorPicker16 operates on the 16-color ANSI palette (ColorName16 enum, values 0–15). Setting SelectedColor to a value outside 0–15 is rejected because there is no corresponding palette slot. The check fires after the ValueChanging CWP event, so handlers can still intercept and cancel.

Source

Thrown at Terminal.Gui/Views/Color/ColorPicker.16.cs:239

            var oldValue = (ColorName16)_selectColorIndex;

            ValueChangingEventArgs<ColorName16> changingArgs = new (oldValue, value);

            if (OnValueChanging (changingArgs) || changingArgs.Handled)
            {
                return;
            }

            ValueChanging?.Invoke (this, changingArgs);

            if (changingArgs.Handled)
            {
                return;
            }

            if (value is < 0 or > (ColorName16)15)
            {
                throw new ArgumentOutOfRangeException (nameof (value), @"SelectedColor must be between 0 and 15.");
            }

            _selectColorIndex = (int)value;
            SetNeedsDraw ();

            ValueChangedEventArgs<ColorName16> changedArgs = new (oldValue, value);
            OnValueChanged (changedArgs);
            ValueChanged?.Invoke (this, changedArgs);

            ValueChangedUntyped?.Invoke (this, new ValueChangedEventArgs<object?> (oldValue, value));
        }
    }

    /// <inheritdoc/>
    public ColorName16 Value { get => SelectedColor; set => SelectedColor = value; }

    /// <inheritdoc/>
    object IValue.GetValue () => SelectedColor;

View on GitHub (pinned to 2e47b11478)

Solutions

  1. Ensure the value is within the ColorName16 enum range (cast-checked or enum member).
  2. Use the ColorName16 enum members directly instead of casting raw ints.
  3. Validate config-sourced color values against 0–15 before assignment.

Example fix

// before
picker.SelectedColor = (ColorName16)idx;
// after
picker.SelectedColor = (ColorName16)Math.Clamp(idx, 0, 15);
Defensive patterns

Strategy: validation

Validate before calling

view.SelectedColor = (ColorName16)Math.Clamp((int)raw, 0, 15);

Type guard

static bool IsValidColor16 (ColorName16 c) => (int)c is >= 0 and <= 15;

Prevention

When it happens

Trigger: Assigning picker.SelectedColor = (ColorName16)20 or any cast from an int outside 0–15; deserializing a color index from config without bounds checking.

Common situations: Casting a 256-color or true-color index into ColorName16; off-by-one from a color array; config/themes with stale values.

Related errors


AI-assisted analysis of tui-cs/Terminal.Gui@2e47b11478 (2026-08-13). Data as JSON: /api/errors/2c6e7c7b1dd821e2. Report an issue: GitHub.