What is the benefit of using C# keywords as identifiers?

Shervan360 1,661 Reputation points
2022-10-29T16:30:41.473+00:00

Hello,

What is the benefit of using C# keywords as identifiers?

namespace ConsoleApp1  
{  
    internal class Program  
    {  
        static void Main(string[] args)  
        {  
            string @for = "Shervan";  
            for (int i = 0; i < @for.Length; i++)  
            {  
                Console.WriteLine(@for[i]);  
            }  
        }  
    }  
}  
Developer technologies | C#
0 comments No comments
{count} votes

Accepted answer
  1. P a u l 10,761 Reputation points
    2022-10-29T17:01:26.333+00:00

    There's no benefit other than descriptiveness, the '@' syntax is just an escape hatch in case you really need to.

    One example of when you might want to do this might be for properties on a class that you're deserialising some JSON into:

       using System.Text.Json;  
       using System.Text.Json.Serialization;  
         
       Player player = JsonSerializer.Deserialize<Player>(@"{  
       	""class"": ""Warrior""  
       }");  
         
       class Player {  
       	public string @class { get; set; }  
       }  
    

    You may not be able to control the format of the incoming JSON. Although even in this scenario you could get around it by using [JsonPropertyName]:

       class Player {  
       	[JsonPropertyName("class")]  
       	public string ClassName { get; set; }  
       }  
    

    It's more of a preference, but I tend to try and avoid keyword collisions and just rename my identifiers.

    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.