46

In VB.NET, you can surround a variable name with brackets and use keywords as variable names, like this:

Dim [goto] As String = ""

Is there a C# equivlent to doing this?

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
Icemanind
  • 47,519
  • 50
  • 171
  • 296

4 Answers4

99
string @string = "";
Dour High Arch
  • 21,513
  • 29
  • 75
  • 90
  • 7
    This is baaad practice IMHO. Variable names should be descriptive. @string is not descriptive. – Daniel Schaffer May 13 '09 at 22:09
  • 42
    @Daneil: it might be bad practice, but it was a very good answer. – Fredrik Mörk May 13 '09 at 22:10
  • I wasn't debating that, I still upvoted... perhaps it was a better comment for the question. – Daniel Schaffer May 13 '09 at 22:12
  • 5
    The purpose of the @ prefix is to allow for interoperability with other .NET languages, see http://stackoverflow.com/questions/724912/does-the-prefix-for-delegates-have-any-special-meaning/724951#724951 – Dirk Vollmar May 13 '09 at 22:13
  • Strange I never realized that string is a keyword... I always thought that it is an identifier alias, but it is apparently a full-rights keyword. – Tamas Czinege May 13 '09 at 22:15
  • All the keywords that are aliases for the system types (int, uint, etc.) are normal C# keywords so they all need to be prefixed. – Lasse V. Karlsen May 13 '09 at 22:16
  • 3
    divo: also, compatability with assemblies compiled against previous versions of C# since new keywords are introduced all the time. – Tamas Czinege May 13 '09 at 22:17
  • 3
    @DrJokepu actually no new reserved keywords have been added, only contextual keywords. So a declaration like "var var = 15;" is valid without the @. It seems this has been intentionally done to avoid backwards compatibility issues. http://blogs.msdn.com/ericlippert/archive/2009/05/11/reserved-and-contextual-keywords.aspx – Timothy Carter May 14 '09 at 02:23
  • 1
    This is also useful when dealing with code generation, where the source does not care about c# keywords. – StingyJack Jun 19 '13 at 20:26
  • @DanielSchaffer `event` is descriptive though – M.kazem Akhgary Dec 31 '18 at 16:35
18

Yes, prefix it with a @

String @goto = "";
Lasse V. Karlsen
  • 380,855
  • 102
  • 628
  • 825
9

Prefix your variable with the @ sign

string @class = "fred";

The @ sign can also be used to prefix a non-escaped string literal:

string a = "fred\"; \\ invalid
string b = @"fred\"; \\ valid. the backslash is part of the literal 'fred\'

I use the latter from time to time but think the using an @ sign to name variables is ugly.

Richard Ev
  • 52,939
  • 59
  • 191
  • 278
andleer
  • 22,388
  • 8
  • 62
  • 82
0

With a @

public IActionResult Submit(Guid? id, string type, string key, string @event)
{

}
Omid Nasri
  • 179
  • 1
  • 10