C# Syntax
Syntax is the set of rules that tells you how to write valid C# code. Once you understand the basic structure, most C# programs will start to look familiar. In this lesson you will learn the key pieces every program is built from.
The structure of a C# program
Look closely at the example below. It contains all of the pieces you will see in almost every C# program you write when you are starting out.
A complete C# program
using System;
class Program
{
static void Main()
{
Console.WriteLine("Understanding C# syntax");
}
}- using System; imports built-in features so you can use them by short names.
- class Program is a container that holds your code.
- static void Main() is the method that runs first when the program starts.
- Console.WriteLine(...) is a statement that prints text to the screen.
- Curly braces { } mark the beginning and end of a block of code.
Statements and semicolons
A statement is a single instruction that tells the program to do something. In C#, every statement must end with a semicolon. Forgetting the semicolon is one of the most common beginner mistakes.
Two statements, two semicolons
using System;
class Program
{
static void Main()
{
Console.WriteLine("Line one");
Console.WriteLine("Line two");
}
}Case sensitivity and whitespace
C# treats uppercase and lowercase letters as different. This means Console and console are not the same thing. C# ignores extra spaces and blank lines, so you are free to indent your code to make it easier to read.
Exercise: C# Syntax
How must each executable statement in C# end?