简体   繁体   中英

Use the long reserved word as a variable name in C#

a bit of an unusual one.. but I was wondering if anyone knew how I could declare a reserved word as a variable. I have the following code, but it does not like my use of the long variable name. I know I could rename it, but for instrest sakes I would like to know if this is at all possible.

private string lat;
private string long;

public string Lat 
{ 
    get
    {
        return lat;                
    }
}

public string Long 
{ 
    get
    {
        return long;
    }
}

Yes, you can if you really want to:

private string @long;

The actual name of the variable (as reported by reflection etc) is just long ; the @ sign tells the compiler to ignore the fact that it's also a keyword.

I would very strongly advise against this, however.

As others have mentioned, you can escape a reserved word with @ .

In your example you don't really need to, I would write the property like this:

private string _long;
public string Long 
{ 
    get
    {
        return _long;
    }
}

And the underscore and the capital L make it compile.

But it's kind of a tradition to call them Lat and Lon , or even better: Latitude and Longitude.

Yes, you can. Using the @ symbol.
This will work, for example: private string @long;
Doing this is highly not recommended, but it is possible.

Not an answer I know as I would steer clear of using reserved words as variable names, but if you insist then at least use the following:

private string lat;
private string @long;

public string Lat 
{ 
    get
    {
        return this.lat;                
    }
}

public string Long 
{ 
    get
    {
        return this.long;
    }
}

I may be late to this party, but I thought I would throw in another place where using a reserved word as a variable name is a good idea!!

I am writing a web control, where I want one of the properties to be "class" in a similar manner as other elements have a "class" property.

So, indeed I will make my property be: "public string @class {get{} set{}}"

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