What does @ do in the name of the variables?

8

In the response code this question in SOen I found an unfamiliar statement line in C #. I tested this line and it works, but I did not understand the meaning of this @ character behind the member name.

// declara "@foo" como uma string com o valor "bar"
var @foo = "bar";
// declara "@abc" como um tipo anônimo com sub valores
var @abc = new {a = 32, b = 64, c = 128}

And I also noticed that it works with classes and types:

class @Program {
    void @Main (string[] args) {
        ...

But by passing the name over the names, Visual Studio's IntelliSense removes @ from names:

And I can also call members with or without @ :

void @Foo () {
    Bar();
    @Bar();
}
void @Bar() {
    ...
}

And even if @bar does not have @ , it can be called with it in the same way.

And I can also declare a method called void :

void @void () { ... }

I know that in Visual Basic, you can declare members with names already reserved by the language using [...] in the names. This is the same thing, only in C #? Or do you have another role besides that?

    
asked by anonymous 08.08.2018 / 06:49

1 answer

12

In this context it is the same as VB using [] (if I am not mistaken it allows more things), it is used in front of identifiers (usually variable names) when the name is equal to that of a keyword, which would cause confusion and the compiler does not know what their intent is, @ makes it clear that it is only an identifier and not the keyword .

Do not use in front of names that are not words reserved by the language. The only thing that makes sense is @void , although I would always try to avoid using names like that. The others use non-privileged names and do not need them, so all other examples do not make sense. Just because it works does not mean it should do.

There is another formatting context for string and it comes before the quotation marks, but nothing to do with what you are asking.

    
08.08.2018 / 06:59