Every language has rules โ grammar for code. C#'s syntax is the set of rules you follow to write valid programs. Let's break down the parts of that "Hello World" program you saw earlier.
Using Directives
At the top of most C# files, you'll see lines starting with using. These tell the compiler which namespaces you want to use. A namespace is like a library of pre-built code. System is the most common one โ it contains basic types and the Console class.
using System; // Brings in the System namespace
using System.Collections.Generic; // Brings in collections like List
Without using System, you'd have to write System.Console.WriteLine() every time. That gets tiresome fast.
Namespace Declaration
You can group your own code into namespaces too. This keeps things organized, especially in large projects:
namespace MyApp {
// Your classes go here
}
Namespaces prevent naming conflicts โ two different people can create a class called Customer as long as they're in different namespaces.
Class and Main Method
Every executable C# program needs a class with a Main method. Main is the entry point โ it's where your program starts executing:
class Program {
static void Main() {
Console.WriteLine("Hello!");
}
}
Here's what each piece means:
class Programโ defines a class named Program. Classes are the building blocks of C#.staticโ means this method belongs to the class itself, not to any specific instance. The runtime calls Main without creating an object first.voidโ means Main doesn't return any value.Main()โ the method name. The runtime looks specifically for a method called Main.
Statements and Blocks
A statement is a complete instruction. Statements end with a semicolon (;). A block is a group of statements wrapped in curly braces ({}).
Console.WriteLine("First"); // This is a statement
Console.WriteLine("Second"); // So is this
{
Console.WriteLine("Inside a block");
Console.WriteLine("Still inside");
}
Curly braces define scope โ what's inside belongs to that block. You'll see them everywhere in C#: after class declarations, method declarations, loops, if statements, and more.
Forgetting a semicolon or mismatching curly braces are the most common beginner mistakes. Visual Studio and VS Code will highlight these errors immediately, so you'll catch them fast.
Try it Yourself โ