开发者

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

开发者 https://www.devze.com 2023-03-14 00:09 出处:网络
In c# you can create variables named identically to a keyword by using @languagekey开发者_Go百科word.

In c# you can create variables named identically to a keyword by using @languagekey开发者_Go百科word.

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


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.


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.


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消