What's the use/meaning of the @ character in variable names in C#?

后端 未结 9 835
小蘑菇
小蘑菇 2020-11-22 01:25

I discovered that you can start your variable name with a \'@\' character in C#. In my C# project I was using a web service (I added a web reference to my project) that was

相关标签:
9条回答
  • 2020-11-22 01:50

    Unlike Perl's sigils, an @ prefix before a variable name in C# has no meaning. If x is a variable, @x is another name for the same variable.

    > string x = "abc";
    > Object.ReferenceEquals(x, @x).Dump();
    True
    

    But the @ prefix does have a use, as you've discovered - you can use it to clarify variables names that C# would otherwise reject as illegal.

    > string string;
    Identifier expected; 'string' is a keyword
    
    > string @string;
    
    0 讨论(0)
  • 2020-11-22 01:52

    The @ symbol allows you to use reserved keywords for variable name. like @int, @string, @double etc.

    For example:

    string @public = "Reserved Keyword used for me and its fine";
    

    The above code works fine, but below will not work:

    string public = "This will not compile";
    
    0 讨论(0)
  • 2020-11-22 01:54

    It simply allows you to use reserved words as variable names. I wanted a var called event the other day. I was going to go with _event instead, but my colleague reminded me that I could just call it @event instead.

    0 讨论(0)
  • 2020-11-22 01:59

    It just lets you use a reserved word as a variable name. Not recommended IMHO (except in cases like you have).

    0 讨论(0)
  • 2020-11-22 01:59

    In C# the at (@) character is used to denote literals that explicitly do not adhere to the relevant rules in the language spec.

    Specifically, it can be used for variable names that clash with reserved keywords (e.g. you can't use params but you can use @params instead, same with out/ref/any other keyword in the language specification). Additionally it can be used for unescaped string literals; this is particularly relevant with path constants, e.g. instead of path = "c:\\temp\\somefile.txt" you can write path = @"c:\temp\somefile.txt". It's also really useful for regular expressions.

    0 讨论(0)
  • 2020-11-22 02:02

    Straight from the C# Language Specification, Identifiers (C#) :

    The prefix "@" enables the use of keywords as identifiers, which is useful when interfacing with other programming languages. The character @ is not actually part of the identifier, so the identifier might be seen in other languages as a normal identifier, without the prefix. An identifier with an @ prefix is called a verbatim identifier.

    0 讨论(0)
提交回复
热议问题