Skip to content

Commit 5297b88

Browse files
Copilotstephentoub
andcommitted
Fix JsonSourceGenerator verbatim identifier handling in property initializers
Fix #116507: C# verbatim identifiers like @else are now correctly handled when generating property initializers for init-only properties. The fix changes PropertyInitializerGenerationSpec.Name to use NameSpecifiedInSourceCode (which includes the @ prefix for reserved keywords) instead of MemberName. Also added a unit test to verify this scenario works correctly. Co-authored-by: stephentoub <[email protected]>
1 parent a00aac9 commit 5297b88

File tree

2 files changed

+28
-1
lines changed

2 files changed

+28
-1
lines changed

src/libraries/System.Text.Json/gen/JsonSourceGenerator.Parser.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1572,7 +1572,7 @@ private void ProcessMember(
15721572

15731573
var propertyInitializer = new PropertyInitializerGenerationSpec
15741574
{
1575-
Name = property.MemberName,
1575+
Name = property.NameSpecifiedInSourceCode,
15761576
ParameterType = property.PropertyType,
15771577
MatchesConstructorParameter = matchingConstructorParameter is not null,
15781578
ParameterIndex = matchingConstructorParameter?.ParameterIndex ?? paramCount++,

src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Unit.Tests/JsonSourceGeneratorTests.cs

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -861,6 +861,33 @@ internal partial class ModelContext : JsonSerializerContext
861861
CompilationHelper.RunJsonSourceGenerator(compilation, logger: logger);
862862
}
863863

864+
#if ROSLYN4_4_OR_GREATER && NET
865+
[Fact]
866+
public void InitOnlyPropertyWithReservedKeywordName_CompilesSuccessfully()
867+
{
868+
// Regression test for https://github.com/dotnet/runtime/issues/116507
869+
// Verbatim identifiers like @else should be correctly handled in property initializers.
870+
871+
string source = """
872+
#nullable enable
873+
using System.Text.Json.Serialization;
874+
875+
public record A
876+
{
877+
public A? @else { get; init; }
878+
}
879+
880+
[JsonSerializable(typeof(A))]
881+
public partial class MyContext : JsonSerializerContext
882+
{
883+
}
884+
""";
885+
886+
Compilation compilation = CompilationHelper.CreateCompilation(source);
887+
CompilationHelper.RunJsonSourceGenerator(compilation, logger: logger);
888+
}
889+
#endif
890+
864891
[Fact]
865892
public void RefStructPropertyWithJsonIgnore_CompilesSuccessfully()
866893
{

0 commit comments

Comments
 (0)