C# Syntax

C# is a free-form, curly-bracket language from the C family, designed at Microsoft by Anders Hejlsberg. Syntax is close to C, C++, and Java: statements end with a semicolon, blocks are delimited by braces, and identifiers are case-sensitive.

Program Structure

A C# source file declares a namespace that contains classes. A class holds members: fields, properties, and methods. Execution starts in a Main method.

Using Directives

The using directive imports a namespace so you can use its types without a full prefix.

using System;                 // Console, Math
using System.Collections.Generic; // List<T>, Dictionary<TKey,TValue>

Namespace

A namespace groups related types and prevents name collisions across assemblies.

namespace SageCode.Demo
{
    // types go here
}

Class

A class is a blueprint for objects. It contains fields, properties, and methods.

class Program
{
    // members go here
}

Main Method

Main is the entry point. The runtime calls it when the program starts.

static void Main(string[] args)  // static: can run without an instance
{
    Console.WriteLine("Hello, World!"); // write one line to the console
}

Code Elements

Statements

Every statement ends with a semicolon ;. Typical statements: declarations, assignments, method calls.

int total = 0;              // declaration + assignment
total = total + 2;          // assignment statement
Console.WriteLine(total);   // method call statement

Blocks

Braces { } group statements into a block. A block defines scope: variables declared inside are not visible outside.

if (total > 0)
{
    int doubled = total * 2;  // 'doubled' lives only inside this block
    Console.WriteLine(doubled);
}
// 'doubled' is not visible here — the block defined its scope

Comments

Comments are for humans — they document intent and are ignored by the compiler. Write why, not what the code obviously does.

  • // single-line comment
  • /* ... */ multi-line comment
  • /// XML documentation comment
// single-line comment
/* multi-line
   comment */
/// <summary>Computes the sum of two integers.</summary>
static int Add(int a, int b) => a + b;

Operators

Operator Table

CategoryOperatorsExample
Arithmetic+ - * / %a + b
Comparison== != > < >= <=a < b
Logical&& || !a && b
Assignment= += -= *= /= %=a += 1
Increment++ --a++

Common Pitfalls

Missing Semicolon

Forgetting the terminal semicolon is the most frequent compile error in beginner code.

Case Sensitivity

Main and main are different identifiers. Class names use PascalCase; local variables use camelCase.

Uninitialized Locals

Local variables must be assigned before first use; the compiler rejects reads of uninitialized variables.