dotnet/wpf · error · InvalidOperationException

SR.Size_CannotModifyEmptySize

Error message

SR.Size_CannotModifyEmptySize

What it means

The Size.Width setter throws InvalidOperationException when the Size is Empty. Size.Empty is a sentinel (width/height = NegativeInfinity) and cannot be mutated; you must replace it with a real Size first.

Solutions

  1. Check IsEmpty and assign a whole new Size instead of setting one property
  2. Initialize fields with new Size(0, 0) rather than Size.Empty when incremental mutation is intended
  3. Use size = new Size(width, size.IsEmpty ? 0 : size.Height) replacement pattern

Example fix

// before
if (size.IsEmpty) size.Width = 100; // throws
// after
size = size.IsEmpty ? new Size(100, 0) : new Size(100, size.Height);
Defensive patterns

Strategy: validation

Validate before calling

if (size.IsEmpty) size = new Size(width, 0); else size = new Size(width, size.Height);

Type guard

bool CanSetDimension(Size s) => !s.IsEmpty;

Try / catch

try { size.Width = w; } catch (InvalidOperationException) { size = new Size(w, 0); }

Prevention

When it happens

Trigger: Assigning size.Width = x where size == Size.Empty, e.g. a field initialized to Size.Empty and mutated one dimension at a time.

Common situations: Incrementally building a size on a control whose size field defaulted to Size.Empty; lazily-initialized layout state mutated before first measure.

Understand the failure class

Background: "Invalid state transition" errors: "status must be X, actually Y", "already rejected/charging/uninstalled", "cannot ... while running" — what they mean when a library rejects your call — this error's family across 31 libraries.

Related errors


AI-assisted analysis of dotnet/wpf@81131a70a4 (2026-09-14). Data as JSON: /api/errors/8be25bea24b579cd. Report an issue: GitHub.

Appendix: source

Thrown at src/Microsoft.DotNet.Wpf/src/WindowsBase/System/Windows/Size.cs:76

            {
                return _width < 0;
            }
        }

        /// <summary>
        /// Width - Default is 0, must be non-negative
        /// </summary>
        public double Width
        {
            get
            {
                return _width;
            }
            set
            {
                if (IsEmpty)
                {
                    throw new System.InvalidOperationException(SR.Size_CannotModifyEmptySize);
                }
                    
                if (value < 0)
                {
                    throw new System.ArgumentException(SR.Size_WidthCannotBeNegative);
                }

                _width = value;
            }
        }

        /// <summary>
        /// Height - Default is 0, must be non-negative.
        /// </summary>
        public double Height
        {
            get
            {

View on GitHub (pinned to 81131a70a4)