C# ยท Chapter 3 of 46

C# Get Started

Every C# console program starts execution from the Main() method, which lives inside a class. Statements are grouped into methods, and methods are grouped into classes.

A C# program is compiled by the .NET compiler into an intermediate language (IL), which the .NET runtime then executes. This gives C# both safety and good performance.

Syntax
using System;

class Program {
  static void Main() {
    // code goes here
  }
}

Anatomy of a C# program

A basic C# program has a using directive for namespaces, a class definition, and a Main() method as the entry point. Statements inside methods end with a semicolon.

Compiling and running

Use `dotnet run` to compile and execute your project in one step during development, or `dotnet build` to just compile it into a binary.

Example 1 (csharp)
using System;

class Program {
  static void Main() {
    Console.WriteLine("My First C# Program");
  }
}
Output
My First C# Program

The using directive brings in Console, and Main() is where execution begins.

Example 2 (csharp)
using System;

class Program {
  static void Main() {
    Console.WriteLine("Line 1");
    Console.WriteLine("Line 2");
  }
}
Output
Line 1
Line 2

Multiple statements execute in the order they appear.

Key points

  • Every C# console program needs a Main() method.
  • using directives bring in namespaces like System.
  • Statements end with a semicolon.
  • `dotnet run` builds and runs your project in one command.
๐Ÿ’ก Note: Newer .NET versions support 'top-level statements', letting you skip the class and Main() boilerplate for simple programs.

๐Ÿ“ Quick Quiz

1. Where does execution start in a C# console app?

2. What does `using System;` provide?

3. Which command builds and runs a C# project?