What does @ do in variable names?

Asked

Viewed 107 times

8

In the response code of this question on Soen I found an unfamiliar statement line on C#. I tested this line and it works, but I didn’t understand the meaning of this character @ behind the member’s 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 his name over the names, Intellisense Visual Studio removes the @ of the names:

Visual Studio mostrando o nome oficial do identificador

And I can also call the members with or without the @:

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

And even if the @bar did not have the @, may be called with him 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 names. That’s the same thing, only in C#? Or it has another function besides that?

  • 1

    In Asp Net MVC we have this in the "namespace" parameter in the route definition call. This is to escape a reserved word .

1 answer

12


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

You should not use in front of names that are not words reserved by language. The only one that makes sense there is the @void, I’d always try to avoid using names like that. The others use non-privileged names and don’t need that, so all the other examples don’t make sense. Just because it works doesn’t mean it should.

There is another context of formatting string and comes before the quotation marks, but nothing to do with what you’re asking.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.