Friday, January 14, 2022

C#: Using a C# keyword as a variable (a.k.a. verbatim identifiers or @ before a keyword variable name)

C# allows keywords to be used as variable names. When a keyword is prefixed by an @  (such as @class), C# interprets that combination as a "verbatim identifier" which means it is a keyword used as a variable name.

A developer worth their salt will not be naming variables after keywords (such @if, @for, @while, @int, and @static). 

I was tasked with posting to a web service and generated the following C# code using the JSON payload for the web service and the generated code looked as follows (not the real payload):

    public class DepartmentRef
    {
        public string departmentRef { get; set; }
        public string @class { get; set; }
        public string @struct { get; set; }
    }

    public class MessageUpdate
    {
        public List<DepartmentRef> departmentRef { get; set; }
    }

    public class Root
    {
        public MessageUpdate messageUpdate { get; set; }
    }

The code in boldface above shows two verbatim identifiers. When a code generator is used, a verbatim identifier may just be a side effect. 

No comments :

Post a Comment