Whitespace

In the C# language, spaces, tabs, and newlines are considered to be “whitespace” (so named because you see only the white of the underlying “page”). Extra whitespace is generally ignored in C# statements. Thus, you can write:

myVariable = 5;

or:

myVariable    =                             5;

and the compiler will treat the two statements as identical. The key is to use whitespace to make the program more readable to the programmer; the compiler is indifferent.

The exception to this rule is that whitespace within a string is treated as literal; it is not ignored. If you write:

Console.WriteLine("Hello World")

each space between “Hello” and “World” is treated as another character in the string. (In this case there is only one space character.)

Problems arise only when you do not leave space between logical program elements that require it. For instance, although the expression:

int myVariable = 5;

is the same as:

int myVariable =5;

it is not the same as:

intmyVariable =5;

The compiler knows that the whitespace on either side of the assignment operator is extra, but the whitespace between the type declaration int and the variable name myVariable is not extra; it is required.

This is not surprising; the whitespace allows the compiler to parse the keyword int rather than some unknown term intmyVariable. You are free to add as much or as little whitespace between int and myVariable as you care to, but there must be at least one whitespace character (typically a space or tab).

Tip

Visual Basic programmers take ...

Get Learning C# now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.