C# syntax is based on C and C++ syntax. In this section, we will describe C#’s elements of syntax, using the following program:
using System; class Test { static void Main() { int x = 12 * 30; Console.WriteLine (x); } }
Identifiers are names that programmers choose for their classes, methods, variables, and so on. These are the identifiers in our example program, in the order they appear:
System Test Main x Console WriteLine
An identifier must be a whole word, essentially made up of Unicode
characters starting with a letter or underscore. C# identifiers are
case-sensitive. By convention, parameters, local
variables, and private fields should be in camel case (e.g., myVariable
), and all other identifiers should
be in Pascal case (e.g., MyMethod
).
Keywords are names reserved by the compiler that you can’t use as identifiers. These are the keywords in our example program:
using class static void int
Here is the full list of C# keywords:
|
|
|
|
If you really want to use an identifier that clashes with a
keyword, you can do so by qualifying it with the @
prefix. For
instance:
class class {...} // Illegal class @class {...} // Legal
The @
symbol doesn’t form
part of the identifier itself. So @myVariable
is the same as myVariable
.
Some keywords are contextual, meaning
they can also be used as identifiers—without an @
symbol. These are:
|
|
|
|
With contextual keywords, ambiguity cannot arise within the context in which they are used.
Literals are primitive pieces of data statically embedded into the
program. The literals in our example program are 12
and 30
.
Punctuators help demarcate the structure of the program. The
punctuators in our program are, ;
,
{
, and }
.
The semicolon terminates a statement. Statements can wrap multiple lines:
Console.WriteLine (1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10);
The braces group multiple statements into a statement block.
An operator transforms and combines expressions.
Most operators in C# are denoted with a symbol, such as the
multiplication operator, *
. The
operators in our program are:
. () * =
The period denotes a member of something (or a decimal point with
numeric literals). The parentheses are used when declaring or calling a method;
empty parentheses are used when the method accepts no arguments. The
equals sign is used for assignment (the double equals
signs, ==
, are used for equality
comparison).
C# offers two different styles of source-code documentation: single-line comments and multiline comments. A single-line comment begins with a double forward slash and continues until the end of the line. For example:
int x = 3; // Comment about assigning 3 to x
A multiline comment begins with /*
and ends with */
. For example:
int x = 3; /* This is a comment that spans two lines */
Comments may embed XML documentation tags (see XML Documentation).