ZetCode

C# lexical structure

last modified November 15, 2026

This article describes the lexical structure of C#: the comments, white space, identifiers, keywords, literals, operators, punctuators, and preprocessor directives that make up the source code.

Like human languages, computer languages have a well-defined lexical structure. Before the compiler can understand a program, it splits the source text into tokens, the smallest meaningful elements of the code. C# has five kinds of tokens: identifiers, keywords, literals, operators, and punctuators. White space and comments are not tokens; they only separate them. Preprocessor directives are processed during this lexical phase as well.

C# source files are Unicode text, usually stored in UTF-8. Identifiers, string literals, and comments may contain characters from any language.

C# comments

Comments clarify the source code for humans; the compiler ignores them. C# has single-line comments starting with //, delimited comments enclosed in /* and */, and documentation comments starting with ///.

Program.cs
/*
    Program.cs
    Shows the three kinds of comments.
*/

// A single-line comment
Console.WriteLine("Comments"); // a comment can follow code

Console.WriteLine(Add(2, /* inline */ 3));

Console.WriteLine("// this is not a comment");

/// <summary>
/// Adds two integers.
/// </summary>
/// <param name="a">The first operand.</param>
/// <param name="b">The second operand.</param>
/// <returns>The sum of the operands.</returns>
static int Add(int a, int b) => a + b;

The program uses all three kinds of comments.

Console.WriteLine("Comments"); // a comment can follow code

A single-line comment extends to the end of the line.

Console.WriteLine(Add(2, /* inline */ 3));

A delimited comment can span several lines or be placed inside a line.

Console.WriteLine("// this is not a comment");

Comment characters inside a string literal are part of the string.

/// <summary>
/// Adds two integers.
/// </summary>

Documentation comments contain XML tags such as <summary> and <param>. IDEs show them as tooltips, and with the GenerateDocumentationFile project property the compiler writes them into an XML file that is distributed with a library.

$ dotnet run
Comments
5
// this is not a comment

Comments cannot be nested

A delimited comment ends at the first */, even if another /* appeared inside it.

Program.cs
/*
    outer comment
    /* inner comment */
    the outer comment has already ended here
*/
Console.WriteLine("unreachable");

We try to put one delimited comment into another.

/* inner comment */

The */ of the inner comment ends the outer comment. The text on the next line is then parsed as code, and the compilation fails. To comment out a block that contains delimited comments, use // on each line; editors do this with a single shortcut.

$ dotnet build
...
Program.cs(4,15): error CS1003: Syntax error, ',' expected

C# white space and line terminators

White space characters are the space, the tab, and a few other Unicode space characters. Line terminators are the carriage return, the line feed, their combination, and the Unicode line and paragraph separators. Outside of string literals, they only separate tokens; the amount of white space does not matter.

Program.cs
int total = 1 +
    2 +
    3;
Console.WriteLine(total);

int a = 1; int b = 2; Console.WriteLine(a + b);

var x=5;var y   =   6;
Console.WriteLine(x*y);

Console.WriteLine("a    b");
Console.WriteLine("a" + "b");

We format statements in unusual ways.

int total = 1 +
    2 +
    3;

A statement can span several lines. In C#, statements end with a semicolon, not with the end of a line.

int a = 1; int b = 2; Console.WriteLine(a + b);

Several statements can be on one line. This compiles, but it is harder to read.

var x=5;var y   =   6;

White space is needed only where two tokens would otherwise merge, as between var and x. Around operators and punctuators, it is optional.

Console.WriteLine("a    b");

Inside a string literal, white space is part of the value and is preserved.

$ dotnet run
6
3
30
a    b
ab

C# identifiers

Identifiers are names of variables, types, methods, and other program elements. An identifier starts with a letter or an underscore, followed by letters, digits, and underscores. Identifiers are case-sensitive.

These are invalid identifiers:

string 123name;      // starts with a digit
int %count;          // contains an invalid character
DateTime birth date; // contains a space
int class;           // a reserved keyword

The following program declares variables with valid names.

Program.cs
string name = "Robert";
string Name = "Julia";
Console.WriteLine($"{name} {Name}");

int _count = 3;
int count2 = 4;
Console.WriteLine(_count + count2);

int @class = 5;
Console.WriteLine(@class);

int var = 6;
string record = "contextual keywords can be identifiers";
Console.WriteLine($"{var}: {record}");

int počet = 7;
Console.WriteLine(počet);

int caf\u00E9 = 8;
Console.WriteLine(café);
string name = "Robert";
string Name = "Julia";

name and Name are two different variables.

int @class = 5;

A reserved keyword cannot be an identifier unless it is prefixed with @. Such verbatim identifiers are useful mainly in generated code or when calling code written in another .NET language.

int var = 6;
string record = "contextual keywords can be identifiers";

Contextual keywords like var, record, value, or async have a special meaning only in certain places, so they are valid identifiers elsewhere.

int caf\u00E9 = 8;
Console.WriteLine(café);

Identifiers can contain letters from any script, like the Slovak počet. A letter can also be written as a Unicode escape sequence; caf\u00E9 and café are the same identifier.

$ dotnet run
Robert Julia
7
5
6: contextual keywords can be identifiers
7
8

C# keywords

Keywords are reserved words with a special meaning, such as if, for, class, int, public, return, true, or null. Reserved keywords can be used as identifiers only with the @ prefix.

Contextual keywords, such as var, async, await, record, required, with, field, or extension, have a meaning only in a specific context. New language features are usually added as contextual keywords, so that existing programs which use these words as names keep compiling.

C# literals

A literal is the textual representation of a value of a built-in type: an integer, a real number, a character, a string, a boolean, or null. C# has no literals for dates or times; those values are created with constructors or parsing methods.

Program.cs
var n1 = 42;
var n2 = 42L;
var n3 = 42u;
var n4 = 0x2A;
var n5 = 0b0010_1010;
var n6 = 1_000_000;

Console.WriteLine($"{n1} {n2.GetType().Name} {n3.GetType().Name} {n4} {n5} {n6}");

var r1 = 3.14;
var r2 = 3.14f;
var r3 = 3.14m;
var r4 = 1.5e3;

Console.WriteLine($"{r1.GetType().Name} {r2.GetType().Name} {r3.GetType().Name} {r4}");

char c1 = 'A';
char c2 = '\u0041';
char c3 = '\x41';
Console.WriteLine($"{c1} {c2} {c3} [{'\t'}]");

string s1 = "C:\\Users\\docs";
string s2 = @"C:\Users\docs";
string s3 = """She said "hi" and left""";
string s4 = $"{n1} is {(n1 > 40 ? "big" : "small")}";
Console.WriteLine($"{s1} {s2} | {s3} | {s4}");

ReadOnlySpan<byte> utf8 = "hi"u8;
Console.WriteLine(utf8.Length);

bool ok = true;
string? nothing = null;
Console.WriteLine($"{ok} [{nothing}] {default(int)}");

The example shows the various literal forms.

var n2 = 42L;
var n3 = 42u;
var n4 = 0x2A;
var n5 = 0b0010_1010;
var n6 = 1_000_000;

An integer literal is int by default. The suffixes L, U, and UL select long, uint, and ulong. The 0x prefix starts a hexadecimal literal, 0b a binary one. The underscore is a digit separator that makes long numbers readable; it does not change the value.

var r1 = 3.14;
var r2 = 3.14f;
var r3 = 3.14m;
var r4 = 1.5e3;

A real literal is double by default; the f suffix makes it a float and m a decimal. The exponent notation 1.5e3 means 1.5 times 10 to the power of 3.

char c1 = 'A';
char c2 = '\u0041';
char c3 = '\x41';

Character literals are in single quotes. A character can also be written as an escape sequence, here three forms of the letter A. The output also shows the tab character '\t' between the brackets.

string s1 = "C:\\Users\\docs";
string s2 = @"C:\Users\docs";
string s3 = """She said "hi" and left""";

In a regular string literal, the backslash starts an escape sequence. In a verbatim string literal, prefixed with @, backslashes are ordinary characters. A raw string literal (C# 11) is enclosed in at least three double quotes and can contain quotes without escaping. The $ prefix makes any of them an interpolated string.

ReadOnlySpan<byte> utf8 = "hi"u8;

The u8 suffix (C# 11) creates a UTF-8 byte sequence instead of a string.

Console.WriteLine($"{ok} [{nothing}] {default(int)}");

true and false are the boolean literals and null is the null literal. A null string prints as an empty string. The default literal gives the default value of a type.

$ dotnet run
42 Int64 UInt32 42 42 1000000
Double Single Decimal 1500
A A A [	]
C:\Users\docs C:\Users\docs | She said "hi" and left | 42 is big
2
True [] 0

C# operators and punctuators

Operators are symbols that perform operations on operands, for example +, *, ==, &&, ??, ?., or =>. Punctuators group and separate parts of the code: braces {} delimit blocks, parentheses () enclose argument lists and expressions, brackets [] are used for indexing, arrays, and attributes, the semicolon ends a statement, and the comma separates list items.

Program.cs
int[] vals = [1, 2, 3, 4, 5];

Console.WriteLine(vals[^1]);
Console.WriteLine(string.Join(", ", vals[1..3]));

string? text = null;
Console.WriteLine(text?.Length ?? -1);

Func<int, int> square = x => x * x;
Console.WriteLine(square(4));

int a = 7;
a += 3;
a <<= 1;
Console.WriteLine(a);

Console.WriteLine(a is > 10 and < 30);
Console.WriteLine(2 + 3 * 4);
Console.WriteLine((2 + 3) * 4);

The example uses a number of operators.

Console.WriteLine(vals[^1]);
Console.WriteLine(string.Join(", ", vals[1..3]));

The hat operator ^ indexes from the end and the range operator .. selects a part of a collection. Note that the same characters can form different tokens: ^ is also the XOR operator.

Console.WriteLine(text?.Length ?? -1);

The null-conditional operator ?. returns null when text is null, and the null-coalescing operator ?? then supplies a default value.

a <<= 1;

The lexer takes the longest possible token, so <<= is one compound assignment operator that shifts left and assigns, not three separate tokens.

Console.WriteLine(2 + 3 * 4);
Console.WriteLine((2 + 3) * 4);

Operators have precedence: multiplication binds more tightly than addition. Parentheses change the order of evaluation. The operator article covers all operators.

$ dotnet run
5
2, 3
-1
16
20
True
14
20

C# preprocessor directives

Preprocessor directives start with # and are processed before the code is compiled. They control conditional compilation, warnings, nullable analysis, and code regions in editors. A directive must be on its own line.

Program.cs
#define TRACE_STEPS

#if DEBUG
Console.WriteLine("Debug build");
#else
Console.WriteLine("Release build");
#endif

#if TRACE_STEPS
Console.WriteLine("Tracing is on");
#endif

#region Calculations
int sum = 0;

for (int i = 1; i <= 10; i++)
{
    sum += i;
}

Console.WriteLine(sum);
#endregion

#pragma warning disable CS0168
int unused;
#pragma warning restore CS0168

#nullable disable
string s = null;
#nullable restore
Console.WriteLine(s is null);

The example uses the most common directives.

#define TRACE_STEPS

#define defines a conditional compilation symbol. It must come before any other code in the file. Symbols can also be defined for the whole project with the DefineConstants property.

#if DEBUG
Console.WriteLine("Debug build");
#else
Console.WriteLine("Release build");
#endif

The DEBUG symbol is defined by the SDK in the Debug configuration, which dotnet run uses by default. The code in the branch that is not taken is not compiled at all.

#region Calculations

#region and #endregion mark a block that editors can collapse. They have no effect on the compiled program.

#pragma warning disable CS0168
int unused;
#pragma warning restore CS0168

#pragma warning suppresses a compiler warning for a part of the file; here the warning about a declared but unused variable.

#nullable disable
string s = null;
#nullable restore

#nullable turns the nullable reference type analysis on or off. Without it, assigning null to a string produces a warning.

We run the program in the Debug and in the Release configuration. In the Release configuration, DEBUG is not defined and the other branch is compiled.

$ dotnet run
Debug build
Tracing is on
55
True
$ dotnet run -c Release
Release build
Tracing is on
55
True

C# naming conventions

Conventions are not enforced by the compiler, but following them makes code consistent with the .NET libraries and with other C# code.

Many of these rules can be checked automatically with an .editorconfig file and the dotnet format tool.

Source

Lexical structure - C# language specification

Identifier names - C# guide

Preprocessor directives - C# reference

In this article we have covered the lexical structure of C#. See also the basics, variable, data type, and operator tutorials.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all C# tutorials.