C# Expressions, Statements and Blocks

ww‮.w‬theitroad.com

In C#, an expression is a piece of code that can be evaluated to a value. Expressions can include literals, variables, operators, method calls, and other expressions. For example, 3 + 4 is an expression that evaluates to the value 7.

A statement is a complete instruction that performs a specific action, such as assigning a value to a variable or calling a method. In C#, most statements end with a semicolon (;). For example, int x = 10; is a statement that declares a variable x of type int and assigns it the value 10.

A block is a group of statements enclosed in curly braces ({ }). A block can contain zero or more statements, and it is often used to group statements together for control flow statements, such as if-else and loops. For example, the following code uses a block to group several statements inside an if-else statement:

int x = 10;
int y = 5;

if (x > y)
{
    Console.WriteLine("x is greater than y");
    y = x;
}
else
{
    Console.WriteLine("y is greater than x");
    x = y;
}

In this code, the if-else statement contains two blocks, one for the if clause and one for the else clause. Each block contains several statements that are executed depending on the condition of the if-else statement.

Blocks are also used to define the body of methods, constructors, and other program elements that require a sequence of statements.

In summary, expressions are code snippets that can be evaluated to a value, statements are complete instructions that perform a specific action, and blocks are groups of statements enclosed in curly braces.