1. Program Structure

A C# program is made of statements grouped into methods, and methods grouped into types (classes, structs, records, interfaces and enums). C# source code is compiled to Intermediate Language (IL) and executed by the .NET runtime (the CLR), which turns it into machine code while the program runs. Execution starts at the entry point: the Main method, or the first top-level statement in modern C# (the compiler generates Main for you).

Every statement ends with a semicolon and blocks are wrapped in curly braces. C# is case-sensitive: Console and console are different names. Namespaces organise types and prevent name clashes, and using directives import them so you can write Console instead of System.Console. Modern .NET project templates switch on implicit usings, so the common namespaces (System, System.IO, System.Linq, System.Collections.Generic, System.Threading.Tasks and others) are already imported. The examples in this course rely on that unless they show a using line.

Comments are ignored by the compiler: // for one line, /* ... */ for several lines, and /// for XML documentation comments that tools display as help. For basic console input and output, Console.WriteLine prints a line, Console.Write prints without moving to a new line, Console.ReadLine reads a line of text and Console.ReadKey waits for a key press.

Key points to remember

  • Create and run a project with the .NET CLI: dotnet new console, then dotnet run. dotnet build compiles without running.
  • A project has one entry point. In a top-level program all type declarations (class, record, enum, struct, interface) must come after the statements.
  • In a top-level program the variable args holds the command-line arguments, exactly like the parameter of Main.
  • Naming conventions: PascalCase for classes, methods, properties and namespaces; camelCase for local variables and parameters; _camelCase for private fields; IPascalCase for interfaces (IPayable).
  • Console.ReadLine always returns text (string, or null when input ends). Convert it with int.Parse or int.TryParse before doing arithmetic.
  • Common mistake: a missing semicolon, an unclosed brace, or wrong capitalisation (console.writeline instead of Console.WriteLine).
  • Numbers, dates and currency are formatted using the computer's culture. Outputs in this course are shown for English (US) culture, so a machine set to another culture may show a comma instead of a decimal point.

Example 1: Hello World (top-level statements)

C#
Console.WriteLine("Hello, World!");
Show output Output
Hello, World!

Example 2: Classic structure with Main

C#
using System;

namespace MyApp
{
    class Program
    {
        static void Main(string[] args)
        {
            // This is a comment
            Console.WriteLine("Program started");
        }
    }
}
Show output Output
Program started

Example 3: Reading input and writing output

C#
Console.Write("Enter your name: ");
string? name = Console.ReadLine();          // user types: Sam
Console.Write("Enter your age: ");
int age = int.Parse(Console.ReadLine()!);   // user types: 21

Console.WriteLine($"Hello, {name}! Next year you will be {age + 1}.");
Console.WriteLine("{0} + {1} = {2}", 2, 3, 2 + 3);   // composite format
Show output Output
Enter your name: Sam
Enter your age: 21
Hello, Sam! Next year you will be 22.
2 + 3 = 5

Example 4: Main with arguments and an exit code

C#
class Program
{
    static int Main(string[] args)
    {
        if (args.Length == 0)
        {
            Console.WriteLine("No arguments");
            return 1;          // a non-zero exit code means "error"
        }
        Console.WriteLine($"Got {args.Length} argument(s): {string.Join(", ", args)}");
        return 0;              // 0 means success
    }
}
Show output Output
(run with no arguments)
No arguments
(run with: dotnet run one two)
Got 2 argument(s): one, two

Example 5: Top-level program with arguments and a type

C#
// Statements come first ...
Console.WriteLine($"Arguments: {args.Length}");
var greeter = new Greeter();
Console.WriteLine(greeter.Greet("Ana"));

// ... type declarations come after them
class Greeter
{
    public string Greet(string name) => $"Hello, {name}";
}
Show output Output
Arguments: 0
Hello, Ana

Example 6: using static, using alias and file-scoped namespace

C#
using static System.Math;           // use Math members without "Math."
using Json = System.Text.Json.JsonSerializer;   // alias for a long name

namespace MyApp.Utilities;          // file-scoped namespace (C# 10): no extra braces

class Demo
{
    public static void Run()
    {
        Console.WriteLine(Sqrt(81));
        Console.WriteLine(Json.Serialize(new[] { 1, 2 }));
    }
}
Show output Output
9
[1,2]

Example 7: Comments and XML documentation

C#
// A single-line comment

/* A comment
   that spans lines */

/// <summary>
/// Adds two numbers. Hover over Add in an editor to see this text.
/// </summary>
/// <param name="a">The first number.</param>
/// <param name="b">The second number.</param>
/// <returns>The sum of a and b.</returns>
static int Add(int a, int b) => a + b;   // end-of-line comment

Console.WriteLine(Add(2, 3));
Show output Output
5