1 · Program Structure & Entry Point

1.1 Skeleton of a Console App

    Every executable C# program needs an entry method (Main) inside a type defined within a namespace.

using System;

namespace HelloWorldApp
{
    class Program
    {
        static void Main(string[] args)        // entry point
        {
            Console.WriteLine("Hello World");  // prints line
        }
    }
}

1.2 File‑Scoped Namespaces (C# 10)

    Omit the { } braces by placing namespace Name; on the first line.

namespace HelloWorldApp;

class Program
{
    static void Main()
        => Console.WriteLine("Hi again!");
}

2 · Using Directives & Global Imports

2.1 Standard using

    Brings a namespace into scope for the current file.

using System.Text;
using System.Collections.Generic;

2.2 Alias Imports

using MyDict = System.Collections.Generic.Dictionary<string,int>;

2.3 Global Usings (.NET 6+)

    Place global using at the top of any .cs file (or in a dedicated GlobalUsings.cs) to include the namespace in every compilation unit.

global using System.IO;

3 · Types, Variables & Literals

3.1 Built‑In Value Types (aliases)

    bool, byte, sbyte, short, ushort, int, uint, long, ulong, char, float, double, decimal

3.2 Declarations

int    age     = 30;
double salary  = 1_000_000.00;    // underscores for readability
var    name    = "Kea";           // implicit typing
decimal? bonus = null;            // nullable value‑type
(char ascii, int code) pair = ('A', 65);   // tuple

3.3 Reference Types & Nullability (C# 8)

#nullable enable
string? middleName = null;
string  firstName  = "Nandi";

3.4 Arrays & Spans

int[] scores = { 90, 85, 99 };
Span<int> slice = scores.AsSpan(1,2);

4 · Operators

4.1 Arithmetic & Assignment

    +, −, *, /, %, +=, -= etc.

4.2 Logical & Bitwise

bool both = a && b;           // short‑circuit AND
int  mask = 0b_1010 | 0b_0101;  // bitwise OR

4.3 Null‑Coalescing & Conditional

string caption = userInput ?? "default";  // ?? operator
result = condition ? value1 : value2;     // ?: operator

5 · Control‑Flow Statements

5.1 Selection Statements

if(score >= 50) { … } else { … }

switch(dayOfWeek)
{
    case DayOfWeek.Monday:
        …
        break;
    default:
        break;
}

5.2 Pattern‑Matching Switch (C# 9)

return e switch
{
    FileNotFoundException  => "Missing file",
    IOException io         => $"I/O error ({io.Message})",
    _                       => "Unknown"
};

5.3 Iteration 

for(int i = 0; i < 10; i++) { … }
foreach(var item in collection) { … }
while(condition) { … }
do { … } while(condition);

6 · Methods & Parameters

6.1 Definition Syntax

static int Add(int x, int y) => x + y;      // expression‑bodied

void Log(string message, bool urgent = false)
{
    if(urgent) Console.Error.WriteLine(message);
    else       Console.WriteLine(message);
}

6.2 params & Named Arguments

int Sum(params int[] nums) => nums.Sum();

var total = Sum(2,3,5,7);
Print(page:1, copies:3);   // named arguments

6.3 Local & Static Local Functions

double Hypot(double a, double b)
{
    static double Squared(double v) => v * v;   // static local func
    return Math.Sqrt(Squared(a) + Squared(b));
}

7 · Classes & Object‑Oriented Features

7.1 Fields, Properties & Constructors

class Person
{
    public string Name  { get; init; }      // init‑only
    public int    Age   { get; set; }

    public Person(string name, int age)
        => (Name, Age) = (name, age);
}

7.2 Inheritance & base

class Employee : Person
{
    public decimal Salary { get; set; }
    public Employee(string n,int a,decimal s) : base(n,a)
        => Salary = s;
}

7.3 Records (C# 9–12)

public record struct Point(int X, int Y);             // value‑based
public record PersonRec(string First,string Last);    // reference record

8 · Interfaces & Abstract Types

8.1 Interface Members (default impl C# 8)

interface ILogger
{
    void Log(string msg);
    void LogWarning(string msg) => Log("[WARN] " + msg);   // default impl
}

8.2 Abstract Classes

abstract class Shape
{
    public abstract double Area();
}

9 · Structs, Enums & Tuples

9.1 Structs

public struct Vector2
{
    public double X, Y;
    public double Magnitude => Math.Sqrt(X*X + Y*Y);
}

9.2 Enums (with flags)

[Flags]
public enum FileAccess
{
    Read = 1, Write = 2, Execute = 4,
    ReadWrite = Read | Write
}

10 · Delegates, Events & Lambdas

10.1 Delegates

delegate int Transformer(int x);

Transformer square = static x => x * x;

10.2 Events

event EventHandler? Completed;

Completed?.Invoke(this, EventArgs.Empty);

10.3 LINQ Lambdas

var odds = Enumerable.Range(1,20)
                     .Where(n => n % 2 == 1)
                     .Select(n => new { n, sq = n*n });

11 · Generics & Constraints

11.1 Generic Class

class Stack<T>
{
    readonly List<T> _items = new();
    public void Push(T item) => _items.Add(item);
    public T    Pop()       => _items[^1];
}

11.2 Constraints (+ where)

T Parse<T>(string s) where T : IParsable<T>
    => T.Parse(s, null);

12 · Exception Handling & Resource Management

12.1 try / catch / finally

try
{
    using var file = File.OpenRead(path);
    …
}
catch(IOException ex) when(ex.HResult == 32)   // filter
{
    …
}
finally { Console.WriteLine("Done"); }

12.2 using Declaration (C# 8)

using var conn = new SqlConnection(cs);   // disposed automatically

13 · Async Programming (Tasks)

13.1 Async Methods

public async Task<string> FetchAsync(Uri url,
                                     CancellationToken ct = default)
{
    using HttpClient client = new();
    return await client.GetStringAsync(url, ct);
}

13.2 async Main

static async Task Main()
{
    var json = await FetchAsync(new("https://api.github.com"));
}

14 · Pattern Matching Enhancements

14.1 Relational & Logical Patterns (C# 9)

static string Grade(int mark) => mark switch
{
    >= 75 and <= 100 => "Distinction",
    >= 50            => "Pass",
    _                => "Fail"
};

14.2 List & Slice Patterns (C# 12)

if(nums is [1, 2, .. var rest])
    Console.WriteLine($"Starts with 1 2, remainder: {string.Join(',',rest)}");

15 · Attributes & Reflection

15.1 Declaring & Using Attributes

[Obsolete("Use NewMethod instead")]
void OldMethod() { … }

15.2 Reading via Reflection

var obsolete = typeof(Foo).GetMethod("OldMethod")!
                          .GetCustomAttribute<ObsoleteAttribute>();

16 · Preprocessor & Compiler Directives

16.1 Conditional Compilation

#define DEBUG
#if DEBUG
    Console.WriteLine("Debug info");
#endif

16.2 Pragmas & Regions

#pragma warning disable CS0168
#region legacy code
…
#endregion

17 · Unsafe Code & Pointers

17.1 Pointer Arithmetic

unsafe
{
    int value = 42;
    int* p = &value;
    Console.WriteLine(*p);   // 42
}

    Note: Requires the /unsafe compiler flag.

18 · Further Reading & Latest Features

    This reference covers C# 1 → 12 (stable as of .NET 8, Nov 2024). Preview features for C# 13 (.NET 9) include params collections, named lambdas, dynamic interceptor attributes, and interleave loops. Consult the official language design notes for up‑to‑date details.