Skip to content

fix: write a C# const local only for a compile-time value [patch] - #172

Merged
matt-edmondson merged 1 commit into
mainfrom
fix/110-csharp-const-local
Oct 6, 2026
Merged

matt-edmondson merged 1 commit into
mainfrom
fix/110-csharp-const-local

Conversation

@matt-edmondson

Copy link
Copy Markdown
Contributor

Summary

CSharpGenerator.GenerateVariableDeclaration wrote const for every IsConstant local with a named type. When the initial value was computed from a parameter or a call, the output was const int doubled = (n * 2);, which fails with CS0133.

  • GoGenerator.IsCompileTimeValue moves to LanguageGeneratorBase as a protected static method, so C# and Go use one rule. Go behaves the same as before.
  • C# now writes const only when IsCompileTimeValue(InitialValue) is true. Otherwise the local is a plain declaration (int doubled = (n * 2);). That matches how the generator already writes an inferred (var) constant, since C# has no readonly locals.

Tests

  • New CSharpConstantLocalTests:
    • NonLiteralConstant_IsAPlainLocal uses the repro from the issue. It fails on main with const int doubled = (n * 2); and passes with this change.
    • LiteralConstant_IsConst checks that a literal constant still comes out as const int max = 7;.
  • The repo has no C# compile harness the way it has for C, C++, Go and Rust, so the new tests check the generated text instead of compiling it.
  • Full Coder.Test suite: 1073 passed, 0 failed.

Fixes #110

🤖 Generated with Claude Code

https://claude.ai/code/session_017USYdQkEy3VLP48Dd4JadP


Generated by Claude Code

CSharpGenerator wrote `const` for every constant local with a named type,
so a constant computed from a parameter or a call came out as
`const int doubled = (n * 2);`, which is error CS0133.

GoGenerator's IsCompileTimeValue moves to LanguageGeneratorBase so both
generators share one rule, and C# now writes `const` only when the initial
value is a literal. Otherwise the local is a plain declaration, which is
already how an inferred constant was written, since C# has no readonly
local.

Fixes #110

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

sonarqubecloud Bot commented Oct 6, 2026

Copy link
Copy Markdown

@matt-edmondson
matt-edmondson merged commit 24dcff6 into main Oct 6, 2026
14 checks passed
@matt-edmondson
matt-edmondson deleted the fix/110-csharp-const-local branch October 6, 2026 06:55
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.

C#: a constant local with a non-literal initial value is emitted as const, which fails to compile with CS0133

2 participants