This lesson is a two part discussion of some syntax rules that are part of the C# language. The first rule is that statements (i.e. lines of code) in a C# program must be terminated by the semicolon “;” character. This lets the compiler know that a particular statement is complete.
int i = 33;
You can break apart your statements into multiple lines. This is allowed by the language. Take a look at how I broke apart the definition and initialization of the variable i into two lines of code below.
int i = 33;
Some C# language constructs do not require a semicolon at the end of a statement. Conditionals and loops are examples of these. Take a look at an “if” statement example.
int i = 33; if (i == 33) i = 10;
Notice that the line of code “if (i == 33)” does not have a semicolon terminator.
The second part of this lesson deals with syntax rules for blocks of code in C#. All blocks of code must be surrounded by open and closed curly braces { }. If you read the previous lessons in the “Getting Started with the language” category, you will have seen an example of curly braces denoting the beginning and end of blocks of code; this example is the Button1_Click method that has both curly braces. Here are the places in a C# source code file that you will use curly braces to denote the start and end of a block of code:
- The class declaration (highest level) - you should see a curly brace on the line following the name of the class and at the end of the file. In some situations you will use curly braces at another level higher than this, which is when Namespaces are used, but more about that in more advanced lessons.
- Method declarations (inside the class) - you should see curly braces denoting the start and end of each Method in a class.
- Blocks of code inside Methods (lowest level) - you will use curly braces for blocks of code inside Methods such as for loops and conditionals. There will be situations where the curly braces are nested, such as for a loop within another loop.
Here is an example where curly braces are used to denote the start and end of a loop block.
for (int i = 0; i < 5; i++) { int myvar = i; txtOutput.Text = myvar.ToString(); }
Notice that inside the curly braces are two statements. Those two statements make up the block of code.
Here is an example of a nested loop so that you can see how nested curly braces can be used.
for (int i = 0; i < 5; i++) { for (int j = 5; j < 10; j++) { int myvar = j; txtOutput.Text = myvar.ToString(); } }
Notice that both the outer and nested for loops use curly braces. You will encounter situations when using conditionals and loops where use of the curly braces is not necessary; this is when the conditional or loop have only one line of code in the block. While it is not required to use curly braces in those situations, you may consider using them anyway since they clearly separate a distinct block of code. This helps some programmers read the code.