C# Cheatsheet

Variables Data Types Strings Numbers Arrays Lists Dictionaries Control Flow Methods Classes Properties Inheritance Interfaces Enums Structs Delegates Events Exceptions File I/O LINQ Async/Await Namespaces Main Method Nullable Types Tuples Pattern Matching

Variables

Variables
int x = 5;
string s = "hello";
bool flag = true;
var y = 10.5;

Nullable Types

Nullable
int? n = null;
if (n.HasValue) { Console.WriteLine(n.Value); }
// Null-coalescing
int x = n ?? 0;

Tuples

Tuple
var t = (Name: "Alice", Age: 30);
Console.WriteLine($"{t.Name} is {t.Age}");
// Deconstruct
(string name, int age) = t;

Pattern Matching

Pattern
object o = 42;
if (o is int i && i > 0) {
  Console.WriteLine($"Positive int: {i}");
}
// Switch pattern
string result = o switch {
  int n when n > 0 => "Positive",
  int n => "Int",
  _ => "Other"
};

Data Types

Types
int a = 1;        // Integer
float b = 2.5f;   // Float
char c = 'A';     // Character
bool d = true;    // Boolean
double e = 3.14;  // Double
string s = "text"; // String
object o = s;     // Any type

Strings

String
string s = "Hello";
string s2 = $"Value: {a}"; // Interpolation
string sub = s.Substring(1, 2);
bool contains = s.Contains("el");
string[] parts = s.Split(',');

Numbers

Numbers
int a = 5;
double b = 3.14;
int sum = a + 2;
double pow = Math.Pow(a, 2);
int parsed = int.Parse("42");

Arrays

Array
int[] arr = {1, 2, 3};
Console.WriteLine(arr[0]);
foreach (int n in arr) Console.WriteLine(n);
Array.Sort(arr);

Lists

List
var list = new List {1, 2, 3};
list.Add(4);
list.Remove(2);
foreach (var n in list) Console.WriteLine(n);

Dictionaries

Dictionary
var dict = new Dictionary();
dict["a"] = 1;
dict.Add("b", 2);
foreach (var kv in dict) Console.WriteLine($"{kv.Key}: {kv.Value}");

Control Flow

Control
if (a > 0) Console.WriteLine("Positive");
else if (a == 0) Console.WriteLine("Zero");
else Console.WriteLine("Negative");

for (int i = 0; i < 5; i++) Console.WriteLine(i);
while (a > 0) a--;
switch (a) {
  case 1: Console.WriteLine("One"); break;
  default: break;
}

Methods

Method
int Add(int a, int b) => a + b;
static void Print(string msg) { Console.WriteLine(msg); }
// Overload
int Add(int a, int b, int c) => a + b + c;

Classes

Class
class Person {
  public string Name;
  public Person(string name) { Name = name; }
  public void Greet() { Console.WriteLine($"Hi, I'm {Name}"); }
}
var p = new Person("Bob");
p.Greet();

Properties

Property
class Car {
  public string Model { get; set; }
  public int Year { get; private set; }
  public Car(string model, int year) { Model = model; Year = year; }
}
var c = new Car("Tesla", 2022);
Console.WriteLine(c.Model);

Inheritance

Inheritance
class Animal {
  public virtual void Speak() { Console.WriteLine("..."); }
}
class Dog : Animal {
  public override void Speak() { Console.WriteLine("Woof"); }
}
Animal a = new Dog();
a.Speak();

Interfaces

Interface
interface IFlyable { void Fly(); }
class Bird : IFlyable {
  public void Fly() { Console.WriteLine("Flying"); }
}
IFlyable f = new Bird();
f.Fly();

Enums

Enum
enum Day { Sun, Mon, Tue }
Day d = Day.Mon;
Console.WriteLine((int)d); // 1

Structs

Struct
struct Point {
  public int X, Y;
  public Point(int x, int y) { X = x; Y = y; }
}
var pt = new Point(1, 2);
Console.WriteLine(pt.X);

Delegates

Delegate
delegate int MathOp(int x, int y);
MathOp add = (a, b) => a + b;
Console.WriteLine(add(2, 3));

Events

Event
class Button {
  public event Action Clicked;
  public void Click() { Clicked?.Invoke(); }
}
var btn = new Button();
btn.Clicked += () => Console.WriteLine("Clicked!");
btn.Click();

Exceptions

Exception
try {
  int x = int.Parse("abc");
} catch (FormatException ex) {
  Console.WriteLine(ex.Message);
} finally {
  Console.WriteLine("Done");
}

File I/O

File
File.WriteAllText("a.txt", "Hello");
string text = File.ReadAllText("a.txt");
foreach (var line in File.ReadLines("a.txt")) Console.WriteLine(line);

LINQ

LINQ
var nums = new List {1,2,3,4};
var even = nums.Where(n => n % 2 == 0).ToList();
var sum = nums.Sum();
var first = nums.FirstOrDefault();

Async/Await

Async
async Task GetDataAsync() {
  await Task.Delay(1000);
  return 42;
}
var result = await GetDataAsync();

Namespaces

Namespace
using System;
namespace MyApp {
  class Program {
    static void Main() { Console.WriteLine("Hi"); }
  }
}

Main Method

Main
class Program {
  static void Main(string[] args) {
    Console.WriteLine("Hello World");
  }
}