This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

C# Programming
.NET 1.1+

C# Variable Naming and the @ Symbol

C# allows very flexible naming of variables and other symbols. This includes the use of alphanumeric characters, a mixture of upper and lower case letters and the underscore symbol. It is even possible to use a variable name that is a reserved word.

Variable Naming

The C# programming language is very flexible when it comes to the naming of variables. In some cases one could argue that it is too flexible, as it allows names that cannot be used by other .NET languages with which you may want to interoperate. However, it is the ability to write classes and structures in multiple languages that requires that unusual naming is permitted.

Most C# variables are named using a mixture of alphanumeric characters, where the letters may be upper case, lower case or a combination of the two. You can also include underscore characters in a name. Some developers use these when a variable name is a combination of several words, placing underscores to represent spaces. Other programmers may use camel case or Pascal case to show the position of new words. Some developers, myself included, like to use an underscore at the start of a private field's name.

The only limitations when combining underscores, letters and numeric digits are that a name cannot start with a number and the name must not be a reserved word. To ensure that items can be accessed from other languages, you should also avoid public members that can only be distinguished by their capitalisation.

All of the following are valid names:

int myVariable;
int myVariable2;
int _myVariable;
int my_variable;
int _;

The four variables below are invalid:

int 123;
int 1Variable;
int _myVariable$;
int foreach;

The @ Symbol

A less commonly used symbol for naming variables is the @ character. This can be positioned at the start of a variable's name. It does not change the name of a variable, which is why if you try to build the following code you see a compiler error indicating that myVariable is defined twice.

int myVariable;
int @myVariable;

The benefit of the @ symbol is that the name it precedes can be a reserved word. This means that we can reference names that are the same as keywords or standard data types. The following two declarations are, therefore, valid. Removing the @ symbol in either case would cause build errors.

int @foreach;
int @int;

Creating variables such as the above is generally considered to be bad practice, as it leads to difficult to read code. However, it is essential to allow C# code to access members from classes developed in .NET languages that have different reserved words.

23 March 2013