C# statement
last modified October 18, 2026
In this article we define statements and show how to work with them in C#.
A computer program largely consists of two building blocks: statements and expressions. An expression is a unit of code that resolves to a value. A statement is an instruction for the program to perform an action. The action can be declaring a variable, assigning a value, calling a method, repeating a block of code, or choosing between branches.
A statement can be a single line of code ended with a semicolon, or a block: a sequence of statements enclosed in curly brackets. A block can be used wherever a single statement is allowed.
The C# language specification groups statements into these categories:
- declaration statements: local variables and constants, local functions
- expression statements: assignments, increments, method calls, object creation,
await - selection statements:
if,switch - iteration statements:
for,foreach,while,do - jump statements:
break,continue,goto,return,throw - exception handling statements:
try/catch/finally,throw checkedanduncheckedstatementslock,using, andfixedstatementsyieldstatements- labeled statements and the empty statement
switch and if are selection statements.
C# declaration and expression statements
In the first example, we have declaration statements and expression statements that call methods.
var name = "John Doe";
var age = 34;
const int Limit = 100;
Console.WriteLine($"{name} is {age} years old");
Console.WriteLine(Environment.Version);
Console.WriteLine(Limit);
We define two variables and a constant and print them.
var name = "John Doe"; var age = 34; const int Limit = 100;
These three lines are declaration statements. A const declaration
creates a compile-time constant.
Console.WriteLine($"{name} is {age} years old");
Console.WriteLine(Environment.Version);
These are expression statements; each invokes a method.
$ dotnet run John Doe is 34 years old 10.0.7 100
C# iteration statements
Iteration statements perform repeated actions or traverse collections. For this
we use the foreach, for, while, and
do keywords.
var words = new List<string> { "falcon", "vulcan", "owl", "stone", "bread" };
foreach (var word in words)
{
Console.WriteLine(word);
}
Console.WriteLine("--------------------------");
for (int i = 0; i < words.Count; i++)
{
Console.WriteLine(words[i]);
}
Console.WriteLine("--------------------------");
int j = 3;
while (j > 0)
{
Console.WriteLine("falcon");
j--;
}
Console.WriteLine("--------------------------");
int k = 0;
do
{
Console.WriteLine($"k = {k}");
k++;
} while (k < 3);
In the example, we have four iteration statements. We go over a list of words with
the foreach and for statements, print a word three
times with while, and count to three with do/while.
The while loop tests its condition before each iteration, so its body
may never run. The do/while loop tests after the body, so the body
always runs at least once.
$ dotnet run falcon vulcan owl stone bread -------------------------- falcon vulcan owl stone bread -------------------------- falcon falcon falcon -------------------------- k = 0 k = 1 k = 2
C# expression statement
The following example uses expression statements to compute a value.
var baskets = 12;
var applesPerBasket = 30;
var total = baskets * applesPerBasket;
total += 5;
total++;
Console.WriteLine($"There are {total} apples");
We compute the total number of apples in all baskets.
var total = baskets * applesPerBasket; total += 5; total++;
The first line is a declaration statement with an initializer, the other two are
expression statements. Only assignments, increments and decrements, method
calls, object creation, and await expressions can be used as
statements. A bare expression such as total * 2; does not compile.
$ dotnet run There are 366 apples
C# selection statements
Selection statements, or conditional statements, execute a branch of code based
on a condition. They are created with the if and switch
statements. The related switch expression is an expression, not a
statement, but it is often used in the same situations.
int n = Random.Shared.Next(-5, 5);
Console.WriteLine(n);
if (n < 0)
{
Console.WriteLine("The n variable is negative");
}
else if (n == 0)
{
Console.WriteLine("The n variable is zero");
}
else
{
Console.WriteLine("The n variable is positive");
}
string kind = n switch
{
< 0 => "negative",
0 => "zero",
_ => "positive"
};
Console.WriteLine(kind);
switch (DateTime.Now.DayOfWeek)
{
case DayOfWeek.Saturday:
case DayOfWeek.Sunday:
Console.WriteLine("weekend");
break;
default:
Console.WriteLine("working day");
break;
}
In the example, only one branch of each construct is executed. The outcome depends on the random value and the current day of the week.
int n = Random.Shared.Next(-5, 5);
Random.Shared is a thread-safe shared instance, so we do not need to
create our own Random.
string kind = n switch
{
< 0 => "negative",
0 => "zero",
_ => "positive"
};
The switch expression uses relational patterns. It must be exhaustive,
which is why the discard pattern _ is present.
switch (DateTime.Now.DayOfWeek)
{
case DayOfWeek.Saturday:
case DayOfWeek.Sunday:
Console.WriteLine("weekend");
break;
default:
Console.WriteLine("working day");
break;
}
The classic switch statement. Unlike in C, a section may not fall
through to the next one; it must end with break, return,
throw, or another jump. Several case labels can share one section.
$ dotnet run -3 The n variable is negative negative weekend
C# empty statement
An empty statement does nothing. It is a lone semicolon, or an empty block
{ }. It is useful when the syntax requires a statement but there is
nothing to do.
int[] vals = [4, 8, 15, 16, 23, 42];
// the loop body is empty; the work is done in the iterator section
int i = 0;
for (; i < vals.Length && vals[i] != 16; i++) { }
Console.WriteLine($"16 is at index {i}");
// a bare semicolon is also an empty statement
while (i-- > 0)
;
Console.WriteLine($"i = {i}");
The first loop searches an array for the value 16; all the work happens in the loop header, so the body is an empty block.
while (i-- > 0)
;
Here the semicolon is an empty statement serving as the loop body. The compiler
warns about such a construct (CS0642) when it appears right after an
if, while, or for on the same line, because
it is usually a typo: if (x > 0); guards nothing. An empty block
{ } expresses the intent more clearly.
$ dotnet run 16 is at index 3 i = -1
C# jump statements
Jump statements transfer control to another place in the code. They are created
with the break, continue, goto,
return, and throw keywords. The yield
statement is used in iterators.
while (true)
{
int num = Random.Shared.Next(1, 30);
Console.Write($"{num} ");
if (num == 22)
{
break;
}
}
Console.WriteLine();
for (int i = 1; i <= 10; i++)
{
if (i % 2 == 0)
{
continue;
}
Console.Write($"{i} ");
}
Console.WriteLine();
IEnumerable<int> Squares(int max)
{
for (int i = 1; i <= max; i++)
{
yield return i * i;
}
}
Console.WriteLine(string.Join(", ", Squares(6)));
static int Sum(int a, int b)
{
return a + b;
}
Console.WriteLine(Sum(3, 4));
The example presents break, continue,
yield return, and return.
while (true)
{
int num = Random.Shared.Next(1, 30);
Console.Write($"{num} ");
if (num == 22)
{
break;
}
}
We jump out of the endless while loop with break when
the number 22 is drawn.
if (i % 2 == 0)
{
continue;
}
The continue statement skips the rest of the current iteration, so
only odd numbers are printed.
IEnumerable<int> Squares(int max)
{
for (int i = 1; i <= max; i++)
{
yield return i * i;
}
}
The yield return statement produces the next element of an iterator
and suspends the method until the next element is requested. The method above is
a local function, which is itself declared with a declaration statement.
static int Sum(int a, int b)
{
return a + b;
}
The return statement ends a method and optionally returns a value.
$ dotnet run 24 1 13 16 7 4 6 29 14 21 3 12 19 17 25 14 9 10 25 19 28 24 13 15 11 29 14 3 15 3 3 21 9 11 3 22 1 3 5 7 9 1, 4, 9, 16, 25, 36 7
The first line is random and differs on each run.
C# exception handling statements
The exception handling statements deal with errors at runtime. We use the
try, catch, finally, and
throw keywords.
int x = 100;
int y = 0;
try
{
int z = x / y;
Console.WriteLine(z);
}
catch (DivideByZeroException e)
{
Console.WriteLine("An exception occurred");
Console.WriteLine(e.Message);
}
finally
{
Console.WriteLine("The finally block always runs");
}
In the program, we divide an integer by zero. The runtime throws a
DivideByZeroException, which we catch. The finally
block runs whether or not an exception occurred, which makes it the place for
cleanup code.
$ dotnet run An exception occurred Attempted to divide by zero. The finally block always runs
Note that integer division by zero throws, while floating-point division by zero yields infinity or NaN.
C# checked and unchecked statements
The checked and unchecked statements control the
overflow-checking context for integral arithmetic operations and conversions.
An arithmetic overflow occurs when a calculation produces a result that is greater in magnitude than the type can represent. By default, C# does not check for overflow in non-constant expressions; the value silently wraps around.
byte a = 254;
try
{
checked
{
for (int i = 0; i < 4; i++)
{
Console.WriteLine(a);
a++;
}
}
}
catch (OverflowException e)
{
Console.WriteLine(e.Message);
}
byte b = 255;
unchecked
{
b++;
}
Console.WriteLine(b);
We increment a byte beyond its maximum value of 255.
In the checked block, the overflow throws an
OverflowException, which we catch. In the unchecked
block, the value wraps around to 0. The compiler flag
<CheckForOverflowUnderflow>true</CheckForOverflowUnderflow>
turns checking on for the whole project.
$ dotnet run 254 255 Arithmetic operation resulted in an overflow. 0
C# using statement
The using statement obtains a resource, executes a block, and then
disposes of the resource, even if an exception is thrown.
var path = Path.Combine(Path.GetTempPath(), "data.txt");
File.WriteAllText(path, "falcon\nowl\nstone\n");
using (var sr = new StreamReader(path))
{
Console.WriteLine(sr.ReadToEnd());
}
// using declaration: disposed at the end of the enclosing scope
using var sr2 = new StreamReader(path);
Console.WriteLine(sr2.ReadLine());
In the example, we create a temporary file and read it twice.
using (var sr = new StreamReader(path))
{
Console.WriteLine(sr.ReadToEnd());
}
The classic form of the using statement disposes the reader at the
closing brace of the block.
using var sr2 = new StreamReader(path);
The using declaration has no block; the resource is disposed at the
end of the enclosing scope, which is the end of the program here.
$ dotnet run falcon owl stone falcon
C# lock statement
The lock statement ensures that only one thread at a time executes a
critical section.
object locker = new();
int counter = 0;
var tasks = Enumerable.Range(0, 4).Select(_ => Task.Run(() =>
{
for (int i = 0; i < 100_000; i++)
{
lock (locker)
{
counter++;
}
}
})).ToArray();
await Task.WhenAll(tasks);
Console.WriteLine(counter);
Four tasks increment a shared counter 100,000 times each. Without the lock, the increments would race and the result would usually be lower than 400,000.
$ dotnet run 400000
C# goto statement
The goto statement transfers execution to a labeled statement.
Console.WriteLine("message 1");
goto next;
Console.WriteLine("message 2");
next:
Console.WriteLine("message 3");
In the example, we skip the second message. The compiler reports an unreachable
code warning for the skipped statement. Use of goto is rare; loops,
break, and continue cover most needs. One legitimate use
is goto case inside a switch statement.
$ dotnet run message 1 message 3
Source
In this article we have worked with statements in C#.
Author
List all C# tutorials.