Search code examples
stringentityref

How to add "ref" as string name in C#


I want to name my string value 'ref' without any capital letters. Since ref is a value i can't do that.

'ref' is a class. I want it to be a name.

 'Ref' with a capital doesn't work in this scenario

Is there a way around this?


Solution

  • As you've discovered, ref is a keyword and can't be used directly in this manner. The usual advice is "don't use keywords as names". For things like deserializing JSON which has a property called "ref" you can often get around it with mapping your otherwise-named property to that JSON property with configuration or a property attribute, depending on the JSON serialization library you're using.

    But if you really do need to use a keyword as a name like this, or if it's just easier than mucking around with things like serialization libraries, the language does provide a way to do that. Simply prefix the name with an @:

    public string @ref { get; set; }
    

    This approach is most commonly seen in things like Razor web pages where we need to specify client-side HTML attributes in server-side C# objects, and a common HTML attribute name is class.