TheDeveloperBlog.com


C# Empty Statement

Empty statement. An empty statement has no effect. It is the simplest and fastest statement. In an empty statement, you type a semicolon. This can be used as a loop body or elsewhere. This helps with empty while-loops with no parentheses.

While

Example. To begin, we look at the empty statement used in the body of a while-loop. The empty statement does nothing, but when you use a while-loop, you must always have a body for that loop—not just an iterative condition.

Sometimes: We have a bool method used as the iterative condition. Then, an empty statement suffices for the loop body.

You could put an empty block instead of an empty statement for the loop body here. Functionality would be equivalent. This is once again a matter of style and you should conform to whatever the rules are—if any exist.

C# program that uses an empty statement

using System;

class Program
{
    static void Main()
    {
	// Use an empty statement as the body of the while-loop.
	while (Method())
	    ;
    }

    static int _number;

    static bool Method()
    {
	// Write the number, increment, and then return a bool.
	Console.WriteLine(_number);
	_number++;
	return _number < 5;
    }
}

Output

0
1
2
3
4


Specification. The C# language specification is the best place to learn about all the statement, expression, and other types. It is not easy reading. It tends to make programs seem much more complex.

The specification helps you understand the language in a conceptual, academic way, rather than a practical way. If you are well-practiced in writing C# programs, the specification could help improve your grasp of the total picture.


Summary. An empty statement in a C# program does nothing. But it can help certain loops conform to the syntactic requirements of the language. There is an elegance, a grace, to using an empty statement.

And: It is as though you, as the programmer, have attained such mastery over the language that you don't even need to type a statement.