A quick-reference instruction sheet covering the fundamentals of C# programming.
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).
.cs extensionnamespace and at least one classMain method;dotnet run or the csc compilerusing System; // import the System namespace
namespace MyApp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
}
}
}
.cs file.// Top-level statement style (C# 9+)
Console.WriteLine("Hello, World!");
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;
| Type | Size | Range / Use |
|---|---|---|
int | 4 bytes | –2,147,483,648 to 2,147,483,647 |
long | 8 bytes | Very large whole numbers |
double | 8 bytes | ~15–17 significant digits |
decimal | 16 bytes | 28–29 significant digits — use for money |
bool | 1 byte | true or false |
char | 2 bytes | Single Unicode character |
string | variable | Immutable sequence of characters |
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
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-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
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 ""
int[] nums = { 10, 20, 30 };
nums[0]; // 10
nums.Length; // 3
int[] sized = new int[5]; // fixed size, all zeros
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
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);
int score = 75;
if (score >= 90)
Console.WriteLine("A");
else if (score >= 75)
Console.WriteLine("B");
else
Console.WriteLine("C or below");
string grade = score switch
{
>= 90 => "A",
>= 75 => "B",
>= 60 => "C",
_ => "F", // default (_)
};
string status = age >= 18 ? "adult" : "minor";
for (int i = 0; i < 5; i++)
Console.WriteLine(i);
// 0 1 2 3 4
var fruits = new List<string> { "apple", "banana", "cherry" };
foreach (string fruit in fruits)
Console.WriteLine(fruit);
int i = 0;
while (i < 5)
Console.WriteLine(i++);
// do-while always runs at least once
do
{
Console.WriteLine(i);
i--;
} while (i > 0);
break to exit a loop, continue to skip to the next iteration.// 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
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 };
| Modifier | Access |
|---|---|
public | Accessible from anywhere |
private | Only within the same class |
protected | Class and derived classes |
internal | Same assembly only |
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!
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;
}
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.");