George Duckett
George Duckett

Reputation: 32428

Is it ever advisable to escape keywords e.g. @class

In c# you can create variables named identically to a keyword by using @languagekeyword.

My question is, when would this be useful? When would the benefits out-weigh the drawbacks?

Upvotes: 2

Views: 478

Answers (5)

Marino Šimić
Marino Šimić

Reputation: 7342

It is not advisable to use variable names that conflict with reserved keyword but sometimes you may want to not follow that rule for readability.

For example:

        var duplicates = from item in Items
                         group item by item.Name into @group
                         where @group.Count() > 1
                         select @group;

It kinda highlights the important part of code.

Other cases come to mind when you need to use third party code that you cannot change.

Upvotes: 0

dtb
dtb

Reputation: 217293

The CLR can be targeted by many different programming languages. One language's identifier is another language's keyword. It would be bad if a class library written in one language couldn't be used from another language because a declared method or property has a name that is a keyword in that language.

Upvotes: 6

DanielB
DanielB

Reputation: 20230

A simple example for a use of these syntax would be in a web application where you may be required to set some attributes to an HTML tag by giving an object like

new { @class = "cssClass" }

This would not be possible without that syntax.

Upvotes: 6

Wouter van Nifterick
Wouter van Nifterick

Reputation: 24086

In general:

When you pick your own names, try to avoid it.

However, sometimes you don't entirely get to pick your own names. For example when you port code, or when you write a wrapper around code that's written in another language. In such cases I think it's better to stick to the original names, so that API descriptions still match with your code, instead of thinking of new names just to avoid a clash with reserved keywords.

Upvotes: 1

Tim Lloyd
Tim Lloyd

Reputation: 38434

It is most useful if you are writing a code generation framework and your underlying model (e.g. a DB) may contain domain objects that use keywords e.g. a db table or field named "event". In this case you can escape all names and there will be no clashes. This makes a code generator forward compatible if new keywords are added.

Upvotes: 3

Related Questions