Skip to content

Reject an expression-bodied property that also has a default value [patch] - #192

Open
matt-edmondson wants to merge 1 commit into
mainfrom
fix/expression-body-with-default-190
Open

matt-edmondson wants to merge 1 commit into
mainfrom
fix/expression-body-with-default-190

Conversation

@matt-edmondson

Copy link
Copy Markdown
Contributor

Fixes #190

What was wrong

When ExpressionBodyFactory was set, PropertyTemplate.WriteTo took the expression-body branch and never looked at DefaultValue. Validate didn't reject the combination either. So DefaultValue = "5" plus ExpressionBodyFactory = cb => cb.Write("x") rendered int P => x;, and the = 5 disappeared without an error. C# has no initialiser on an expression-bodied property, so there was no correct way to write both.

Change

  • PropertyTemplate.Validate now throws InvalidOperationException, naming the property, when ExpressionBodyFactory is set and the template has a default value (HasDefaultValue, which also counts a quoted empty string).
  • ClassTemplate.Validate already validates every member before writing, so AddClass now refuses such a class before writing anything.
  • Added the new case to the <exception> doc on WriteTo.

Tests

  • AnExpressionBodyWithADefaultValueIsRejectedBeforeAnythingIsWritten: the issue's repro throws, the message names 'P', and the CodeBlocker keeps exactly what it held before.
  • AClassWithAnExpressionBodiedPropertyThatHasADefaultValueWritesNothing: inside a class, AddClass throws and nothing is written.
  • With the PropertyTemplate.cs change reverted, both new tests fail ("no exception was thrown").
  • Full suite on Linux / .NET 10: 331/331 passed.

Generated by Claude Code

…atch]

PropertyTemplate wrote the expression body and silently dropped DefaultValue,
since C# cannot give an expression-bodied property an initialiser. Validate
now refuses the combination before anything is written, so a class holding
such a property is refused by AddClass up front too.

Fixes #190

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017vfJW5kkYGVswnWUL9YgPE
@sonarqubecloud

sonarqubecloud Bot commented Nov 5, 2026

Copy link
Copy Markdown

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

A property with both ExpressionBodyFactory and DefaultValue silently drops the default: writes int P => x; with no error

2 participants