Back to C# Examples

Basic C#

A quick-reference instruction sheet covering the fundamentals of C# programming.

Contents

  1. What is C#?
  2. Program Structure
  3. Variables & Data Types
  4. Operators
  5. Strings
  6. Collections
  7. Control Structures
  8. Loops
  9. Methods
  10. Classes & OOP
  11. Interfaces & Inheritance
  12. Exception Handling

1. What is C#?

C# (pronounced "C sharp") is a modern, object-oriented language developed by Microsoft and part of the .NET platform. It is statically typed, compiled, and runs on the .NET runtime (CLR).

2. Program Structure

using System;           // import the System namespace

namespace MyApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello, World!");
        }
    }
}
C# 9+ supports top-level statements — you can omit the class and Main boilerplate and write code directly in a .cs file.
// Top-level statement style (C# 9+)
Console.WriteLine("Hello, World!");

3. Variables & Data Types

int     age     = 30;
double  price   = 9.99;
float   temp    = 36.6f;
bool    active  = true;
char    grade   = 'A';
string  name    = "Alice";
decimal money   = 99.95m;   // high-precision — use for currency
object  anything = 42;      // base type of all types

// var — type inferred by the compiler
var city  = "NYC";           // inferred as string
var count = 10;              // inferred as int

// Constants
const int MAX = 100;

// Nullable types — can hold null
int? maybe = null;
string? optName = null;
TypeSizeRange / Use
int4 bytes–2,147,483,648 to 2,147,483,647
long8 bytesVery large whole numbers
double8 bytes~15–17 significant digits
decimal16 bytes28–29 significant digits — use for money
bool1 bytetrue or false
char2 bytesSingle Unicode character
stringvariableImmutable sequence of characters

4. Operators

Arithmetic

int a = 10, b = 3;
a + b    // 13
a - b    // 7
a * b    // 30
a / b    // 3  — integer division
a % b    // 1  — modulus
a++      // post-increment

Comparison & Logical

x == y   // equal
x != y   // not equal
x <  y   // less than
x >  y   // greater than

a && b   // logical AND
a || b   // logical OR
!a        // logical NOT

Null-related Operators

// Null-coalescing — use right side if left is null
string display = name ?? "Guest";

// Null-coalescing assignment
name ??= "Guest";

// Null-conditional — safe member access
int? len = name?.Length;   // null if name is null

5. Strings

string first = "Alice";
string last  = "Smith";

// Concatenation
first + " " + last               // "Alice Smith"

// String interpolation (preferred)
$"Hello, {first}!"                // "Hello, Alice!"
$"Age: {age + 1}"                 // expressions work

// Verbatim string — backslashes are literal
@"C:\Users\Alice\Documents"

// Common string methods
first.Length                        // 5
first.ToUpper()                     // "ALICE"
first.ToLower()                     // "alice"
first.Trim()                        // strip whitespace
first.Contains("lic")              // true
first.StartsWith("Al")             // true
first.Replace("l", "r")            // "Arice"
first.Substring(1, 3)              // "lic"
first.Split(',')                   // string array
string.Join(", ", arr)             // join array to string
string.IsNullOrEmpty(name)         // true if null or ""

6. Collections

Arrays

int[] nums = { 10, 20, 30 };
nums[0];                   // 10
nums.Length;               // 3

int[] sized = new int[5];  // fixed size, all zeros

List<T>

using System.Collections.Generic;

var fruits = new List<string> { "apple", "banana", "cherry" };

fruits.Add("date");          // append
fruits.Remove("banana");     // remove by value
fruits.Count;                // number of items
fruits[0];                   // "apple"
fruits.Contains("apple");   // true
fruits.Sort();               // sort in place

Dictionary<K, V>

var ages = new Dictionary<string, int>
{
    { "Alice", 30 },
    { "Bob",   25 },
};

ages["Alice"];              // 30
ages["Carol"] = 28;         // add or update
ages.ContainsKey("Bob");   // true
ages.Remove("Bob");

// Safe lookup
if (ages.TryGetValue("Alice", out int val))
    Console.WriteLine(val);

7. Control Structures

if / else if / else

int score = 75;

if (score >= 90)
    Console.WriteLine("A");
else if (score >= 75)
    Console.WriteLine("B");
else
    Console.WriteLine("C or below");

switch expression (C# 8+)

string grade = score switch
{
    >= 90 => "A",
    >= 75 => "B",
    >= 60 => "C",
    _      => "F",    // default (_)
};

Ternary

string status = age >= 18 ? "adult" : "minor";

8. Loops

for

for (int i = 0; i < 5; i++)
    Console.WriteLine(i);
// 0 1 2 3 4

foreach

var fruits = new List<string> { "apple", "banana", "cherry" };

foreach (string fruit in fruits)
    Console.WriteLine(fruit);

while & do-while

int i = 0;
while (i < 5)
    Console.WriteLine(i++);

// do-while always runs at least once
do
{
    Console.WriteLine(i);
    i--;
} while (i > 0);
Use break to exit a loop, continue to skip to the next iteration.

9. Methods

// Basic method
static string Greet(string name)
{
    return $"Hello, {name}!";
}

// Expression-bodied method (single expression)
static int Add(int a, int b) => a + b;

// Optional / default parameters
static string Greet(string name = "World") => $"Hello, {name}!";

// out parameter — return multiple values
static void Divide(int a, int b, out int quotient, out int remainder)
{
    quotient  = a / b;
    remainder = a % b;
}

Divide(10, 3, out int q, out int r);  // q=3, r=1

// params — variable number of arguments
static int Sum(params int[] nums) => nums.Sum();
Sum(1, 2, 3, 4);   // 10

10. Classes & OOP

public class Person
{
    // Properties (preferred over public fields)
    public string Name  { get; set; }
    public int    Age   { get; set; }
    private string _secret = "hidden";

    // Constructor
    public Person(string name, int age)
    {
        Name = name;
        Age  = age;
    }

    // Method
    public string Describe() =>
        $"{Name} is {Age} years old.";

    // Override ToString
    public override string ToString() => Name;
}

// Instantiate
var p = new Person("Alice", 30);
Console.WriteLine(p.Describe());   // Alice is 30 years old.

// Object initialiser syntax
var p2 = new Person("Bob", 25) { Age = 26 };
ModifierAccess
publicAccessible from anywhere
privateOnly within the same class
protectedClass and derived classes
internalSame assembly only

11. Interfaces & Inheritance

Inheritance

public class Animal
{
    public string Name { get; set; }

    public virtual string Speak() => "...";
}

public class Dog : Animal
{
    public override string Speak() => $"{Name} says: Woof!";
}

var dog = new Dog { Name = "Rex" };
Console.WriteLine(dog.Speak());    // Rex says: Woof!

Interfaces

public interface IShape
{
    double Area();
    double Perimeter();
}

public class Circle : IShape
{
    public double Radius { get; set; }
    public double Area()      => Math.PI * Radius * Radius;
    public double Perimeter() => 2 * Math.PI * Radius;
}
A class can inherit from only one base class, but it can implement multiple interfaces.

12. Exception Handling

try
{
    int[] arr = { 1, 2, 3 };
    Console.WriteLine(arr[10]);   // throws IndexOutOfRangeException
}
catch (IndexOutOfRangeException ex)
{
    Console.WriteLine($"Index error: {ex.Message}");
}
catch (Exception ex)              // catch-all
{
    Console.WriteLine($"Error: {ex.Message}");
}
finally
{
    Console.WriteLine("Always runs — good for cleanup.");
}

// Throw your own exception
if (age < 0)
    throw new ArgumentException("Age cannot be negative.");
Only catch exceptions you can meaningfully handle. Let unexpected exceptions propagate rather than swallowing them silently.