简体   繁体   中英

C# keyword-like variables

We have the following cycle in the code:

foreach (var event in events)
{
...
{

Of cources we can't name variable "event" as it is a keyword. Which way is a more appropriate in this kind of cases: to use @ prefix (@event) or to use another name like "currentEvent"?

Definitely use another name.

The keyword variables are really cool feature of C# but they should be used for interoperability.

I would usually recoil from using the @ prefix. (I sometimes use it to name the first parameter in an extension method @this , but even that's pretty rare.)

See if you can think of any other way of describing the event. Is it a particular kind of event, for example?

Because the @ prefix is so rare, it may confuse other developers. I would advise to use another variable name here.

It is different when the name is part of your public interface. In that case, you want to use the right name, even if it is a keyword. However, if you do this you make it hard for people who want to use your interface, as they have to use @ everywhere.

Personally I dislike using @ and _ as a prefix just to be able to use a keyword. I think in most cases you can rename it, either:

foreach (var uiEvent in uiEvents)
{
...
{

(more specific)

or

foreach (var evt in events)
{
...
{

(some kind of shorthand)

Personally, I would advise naming it based on its context and what it represents. If it represents an event that is to be executed, I would probably name it something like executableEvent , as an example.

Alternately, if you are just using it locally to invoke each event - for example - it may be acceptable to give it an abbreviated version of the name such as evt . Normally I would vote against this sort of naming convention, but if it is just temporary and local others may deem it fine.

我会使用e_eventcurrentEvent

I really would advise you against using @ so you have to choose another name. Like some said, you can type your name to a more specific type of event

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM