Understanding the difference between expressions and statements
At its core, an expression in C# is just a piece of code that evaluates to a value. Simple expressions include constants, variables, and method calls. On the other hand, a statement is a standalone unit of code that performs an action. In essence, it is an executable instruction. The best way to understand something is through practice. So, let’s not delay anymore and look at expressions and statements through examples.
Example of expressions
Consider the following C# code:
var pagesPerChapter = 20; var totalBookPages = pagesPerChapter * 10;
In this snippet, 20, pagesPerChapter
, 10
, and pagesPerChapter * 10
are all expressions. Each of these pieces of code evaluates to a value.
Example of statements
Now, let’s identify statements:
var pagesPerChapter = 20; var totalBookPages = pagesPerChapter * 10;
Here, var pagesPerChapter = 20; and var totalBookPages = pagesPerChapter * 10; are statements. The first line instructs the program to declare a pagesPerChapter variable and initialize it with a value of 20. The second line instructs the program to multiply the value of pagesPerChapter by 10 and save it in the totalBookPages
variable. Both are standalone code units that perform actions, fitting our definition of a statement.
Key differences between expressions and statements
Although statements and expressions can sometimes look similar, remember that an expression produces a value and can be used in larger expressions. In contrast, a statement performs an action and serves as a part of a method or program structure.
In C#, every expression can be turned into a statement, but not every statement can be an expression. For example, x = y + 2
is a statement where y + 2
is an expression. However, a for
loop or an if
statement cannot be expressions.
Guided exercise – finding expressions and statements in sample code
Let’s exercise your knowledge. Can you find and count all the expressions and statements in a slightly more complex code snippet?
int bookCount = 5; for(int chapter = 1; chapter <= bookCount; chapter++) { var wordCount = chapter * 1000; Console.WriteLine($"Chapter {chapter} contains {wordCount} words."); }
Here, we have 8 expressions and 4 statements. Specifically:
- Expressions:
5
,1
,chapter
,bookCount
,chapter <= bookCount
,chapter++
,1000
,chapter * 1000
,chapter
,wordCount
, and$"Chapter {chapter} contains {
wordCount} words."
- Statements:
int bookCount = 5;
,for(int chapter = 1; chapter <= bookCount; chapter++)
,var wordCount = chapter * 1000;
, andConsole.WriteLine($"Chapter {chapter} contains {
wordCount} words.");
Understanding the difference between expressions and statements helps you write better, clearer code. As you keep learning C#, you’ll get used to these basics and be able to make better software. Keep going with this knowledge, and let’s keep exploring functional programming.