What's the Use/Meaning of the @ Character in Variable Names in C#

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

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.

What does placing a @ in front of a C# variable name do?

It's just a way to allow declaring reserved keywords as vars.

void Foo(int @string)

What does the @ symbol before a variable name mean in C#?

The @ symbol allows you to use reserved word. For example:

int @class = 15;

The above works, when the below wouldn't:

int class = 15;

What does '@' char mean before parameter name in method declaration?

It allows reserved words to be used as identifiers. It is usually used by code generators which may be using source names from systems with different keywords than the target language e.g. table names and sproc argument names.

What does variable names beginning with _ mean?

There's no language-defined meaning - it's just a convention some people use to distinguish instance variables from local variables. Other variations include m_foo (and s_foo or g_foo or static variables) or mFoo; alternatively some people like to prefix the local variables (and parameters) instead of the instance variables.

Personally I don't use prefixes like this, but it's a style choice. So long as everyone working on the same project is consistent, it's usually not much of an issue. I've seen some horribly inconsistent code though...

C# @ symbol in variable names

class is a reserved word in C# to denote a new type. You can't have a variable name that is a reserved word, so you use @ to 'escape' the symbol.

AKA:

int int = 4; // Invalid
int @int = 4; // Valid

What is the purpose of @ as part of a member name in C#?

You are correct. See C# Keywords, section 2.4.2 Identifiers of the language specification, or string (C# Reference).

From the keywords topic:

Keywords are predefined, reserved
identifiers that have special meanings
to the compiler. They cannot be used
as identifiers in your program unless
they include @ as a prefix. For
example, @if is a valid identifier but
if is not because if is a keyword.

How can I use a variable name called object?

You can name your field @object:

public class FacebookObjectDataData
{
public FacebookObjectDataDataObject @object { get; set; }

public FacebookObjectDataData()
{
}
}

So it will not be marked as error. You can do it with other restricted names.

For more read here http://msdn.microsoft.com/en-us/library/aa664670.aspx



Related Topics



Leave a reply



Submit