C#
keyword
property name
coding
programming tips

How do I use a C keyword as a property name?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

In C#, keywords such as class, event, and namespace are reserved, so using them as property names can trigger compile errors. This becomes common when your model must match an external JSON contract that you cannot rename. The best approach is usually to keep internal code readable and use serializer mapping for wire compatibility.

Option 1: Escaped Identifiers with @

C# lets you use a keyword as an identifier by prefixing it with @. This is syntactic escaping in source code only.

csharp
1using System;
2
3public class RawContract
4{
5    public string @class { get; set; } = "gold";
6    public string @event { get; set; } = "created";
7}
8
9var model = new RawContract();
10Console.WriteLine(model.@class);
11Console.WriteLine(model.@event);

This is the smallest fix, especially for generated code where exact field names matter.

Option 2: Readable Internal Names with JSON Mapping

For application code, readable names are easier to maintain. Use attributes to map internal names to external keyword fields.

csharp
1using System;
2using System.Text.Json;
3using System.Text.Json.Serialization;
4
5public class ApiEvent
6{
7    [JsonPropertyName("class")]
8    public string ClassName { get; set; } = "gold";
9
10    [JsonPropertyName("event")]
11    public string EventType { get; set; } = "created";
12}
13
14var json = "{\"class\":\"silver\",\"event\":\"updated\"}";
15var dto = JsonSerializer.Deserialize<ApiEvent>(json);
16Console.WriteLine(dto?.ClassName);
17Console.WriteLine(dto?.EventType);

This keeps domain language clear while preserving API compatibility.

Newtonsoft.Json Equivalent

If your project still uses Newtonsoft.Json, use JsonProperty instead of JsonPropertyName.

csharp
1using Newtonsoft.Json;
2
3public class LegacyDto
4{
5    [JsonProperty("namespace")]
6    public string NamespaceValue { get; set; } = "main";
7
8    [JsonProperty("operator")]
9    public string OperatorName { get; set; } = "system";
10}

Avoid mixing serializer attributes from both libraries in one model unless migration rules are clearly documented.

Runtime Reflection Behavior

Escaping with @ does not change the runtime member name in metadata. Reflection sees the logical identifier without @.

csharp
1using System;
2using System.Reflection;
3
4public class EscapedSample
5{
6    public string @default { get; set; } = "x";
7}
8
9foreach (PropertyInfo p in typeof(EscapedSample).GetProperties())
10{
11    Console.WriteLine(p.Name); // prints default
12}

That is why explicit serializer attributes are still important when external naming differs from project conventions.

A consistent naming policy prevents confusion in code reviews and onboarding.

  1. Generated transport models may keep escaped keyword names.
  2. Handwritten domain models should prefer readable names.
  3. Mappings should be explicit with serializer attributes.
  4. Contract tests should validate serialization and deserialization.

This separation makes code easier to reason about while keeping protocol fidelity.

Migration Strategy for Existing Code

If your codebase has mixed styles, migrate incrementally:

  • Identify keyword-like names across DTO classes.
  • Decide which classes are transport-only and which are domain-facing.
  • Apply mapping attributes for domain-facing classes.
  • Add unit tests for expected JSON field names.

Example serialization test:

csharp
1using System.Text.Json;
2
3var dto = new ApiEvent { ClassName = "bronze", EventType = "deleted" };
4var jsonOut = JsonSerializer.Serialize(dto);
5
6if (!jsonOut.Contains("\"class\"") || !jsonOut.Contains("\"event\""))
7    throw new Exception("Contract field names are incorrect");

Testing contract shape directly catches breaking changes early.

Common Pitfalls

  • Forgetting the @ prefix on one usage and getting inconsistent compile errors.
  • Assuming escaped identifiers automatically control JSON field names.
  • Exposing keyword-heavy naming across internal domain logic.
  • Mixing System.Text.Json and Newtonsoft attributes without a migration plan.
  • Skipping contract tests after serializer or naming policy changes.

Summary

  • C# supports keyword identifiers via the @ escape syntax.
  • For maintainability, prefer readable property names plus explicit JSON mapping.
  • Escaped syntax affects source code, not runtime metadata naming.
  • Keep a clear boundary between generated transport models and domain models.
  • Add contract tests to protect wire-format compatibility during refactors.

Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.