C# Cheat Sheet

Variables and Data Types

Use int, string, bool, etc. to declare variables. Use var for type inference.

int x = 10;
string name = "C#";
bool isActive = true;
var score = 99.5;

Constants and Literals

const defines compile-time constants. readonly for runtime constants.

const double Pi = 3.1415;
readonly string appName = "MyApp";

Type Casting and Conversion

int i = 123;
double d = i; // implicit
int j = (int)d; // explicit
string s = i.ToString();
int parsed = int.Parse("123");

Operators (Arithmetic, Logical, Comparison)

int a = 5 + 3;
bool b = (a > 3) && (a < 10);
bool equal = (a == 8);
int inc = ++a;

String Manipulation and Interpolation

string name = "World";
string message = $"Hello, {name}!";
string upper = name.ToUpper();

Nullable Types

Use ? to declare nullable value types.

int? age = null;
if (age.HasValue) {
  Console.WriteLine(age.Value);
}

Comments

// This is a single-line comment
/* This is a
   multi-line comment */

if / else / switch

int number = 10;
if (number > 0) {
  Console.WriteLine("Positive");
} else {
  Console.WriteLine("Non-positive");
}

switch (number) {
  case 1:
    Console.WriteLine("One");
    break;
  default:
    Console.WriteLine("Other");
    break;
}

Loops (for, while, do-while, foreach)

for (int i = 0; i < 5; i++) {
  Console.WriteLine(i);
}

int j = 0;
while (j < 5) {
  Console.WriteLine(j);
  j++;
}

do {
  Console.WriteLine(j);
  j++;
} while (j < 10);

foreach (var item in new int[] { 1, 2, 3 }) {
  Console.WriteLine(item);
}

break / continue / goto

for (int i = 0; i < 10; i++) {
  if (i == 3) continue;
  if (i == 5) break;
  Console.WriteLine(i);
}

goto skip;
Console.WriteLine("This won't print");
skip:
Console.WriteLine("Skipped to here");

Method Declaration and Overloading

void Greet(string name) {
  Console.WriteLine($"Hello, {name}");
}

void Greet() {
  Console.WriteLine("Hello, Guest");
}

Optional and Named Parameters

void Display(string message = "Default", int count = 1) {
  for (int i = 0; i < count; i++) {
    Console.WriteLine(message);
  }
}

Display(count: 3, message: "Hi");

ref / out / in keywords

void Update(ref int x) {
  x += 10;
}

void Initialize(out int x) {
  x = 100;
}

void Print(in int x) {
  Console.WriteLine(x);
}

Lambda Expressions

Func add = (a, b) => a + b;
Console.WriteLine(add(2, 3));

Local Functions

void Outer() {
  void Inner() {
    Console.WriteLine("Hello from inner");
  }
  Inner();
}

Classes and Objects

class Person {
  public string Name;
  public void Greet() {
    Console.WriteLine($"Hi, I'm {Name}");
  }
}

Person p = new Person();
p.Name = "Alice";
p.Greet();

Constructors and Destructors

class Car {
  public Car() {
    Console.WriteLine("Car created");
  }

  ~Car() {
    Console.WriteLine("Car destroyed");
  }
}

Inheritance

class Animal {
  public void Speak() => Console.WriteLine("Generic sound");
}

class Dog : Animal {
  public void Bark() => Console.WriteLine("Woof");
}

Polymorphism

class Base {
  public virtual void Show() => Console.WriteLine("Base");
}

class Derived : Base {
  public override void Show() => Console.WriteLine("Derived");
}

Abstraction

abstract class Shape {
  public abstract void Draw();
}

class Circle : Shape {
  public override void Draw() => Console.WriteLine("Draw Circle");
}

Encapsulation

class BankAccount {
  private decimal balance;

  public void Deposit(decimal amount) {
    if (amount > 0) balance += amount;
  }
}

Interfaces

interface ILogger {
  void Log(string message);
}

class ConsoleLogger : ILogger {
  public void Log(string message) => Console.WriteLine(message);
}

Static Members

class Utility {
  public static int Add(int a, int b) => a + b;
}

Properties and Indexers

class Book {
  public string Title { get; set; }
}

class Library {
  private string[] books = new string[10];
  public string this[int index] {
    get => books[index];
    set => books[index] = value;
  }
}

Access Modifiers

public, private, protected, internal, and protected internal define access levels.

public class MyClass {
  private int secret;
  protected void Reveal() {}
}

Delegates

delegate int Operation(int x, int y);
Operation add = (a, b) => a + b;
Console.WriteLine(add(3, 4));

Events

class Button {
  public event Action Click;
  public void Press() => Click?.Invoke();
}

Generics

class Box {
  public T Value;
}

var intBox = new Box { Value = 10 };

Extension Methods

static class Extensions {
  public static int Square(this int x) => x * x;
}

int value = 5;
Console.WriteLine(value.Square());

Anonymous Types

var person = new { Name = "John", Age = 30 };
Console.WriteLine(person.Name);

Tuples

var tuple = (Name: "Jane", Age: 28);
Console.WriteLine(tuple.Name);

Nullable Reference Types

#nullable enable
string? optional = null;
if (optional != null) {
  Console.WriteLine(optional.Length);
}

Pattern Matching

object obj = 42;
if (obj is int n && n > 40) {
  Console.WriteLine($"Matched: {n}");
}

LINQ (Select, Where, GroupBy, etc.)

var numbers = new[] { 1, 2, 3, 4 };
var evens = numbers.Where(n => n % 2 == 0);
var squares = numbers.Select(n => n * n);

foreach (var s in squares) Console.WriteLine(s);

Exception Handling

try / catch / finally

try {
  int x = 0;
  int y = 10 / x;
} catch (DivideByZeroException ex) {
  Console.WriteLine("Cannot divide by zero");
} finally {
  Console.WriteLine("Done");
}

throw

throw new InvalidOperationException("Invalid action");

Custom Exceptions

class MyException : Exception {
  public MyException(string msg) : base(msg) {}
}

Collections and Data Structures

int[] array = { 1, 2, 3 };
List list = new List();
Dictionary dict = new();
HashSet set = new();
Queue queue = new();
Stack stack = new();

Span<T> and Memory<T>

Span span = stackalloc int[3] { 1, 2, 3 };
Console.WriteLine(span[0]);

File Reading and Writing

File, StreamReader, StreamWriter

string path = "example.txt";
File.WriteAllText(path, "Hello World");
string content = File.ReadAllText(path);

using StreamWriter writer = new(path);
writer.WriteLine("Line 1");

using StreamReader reader = new(path);
string line = reader.ReadLine();

Path and Directory

string fullPath = Path.Combine("folder", "file.txt");
if (!Directory.Exists("folder")) Directory.CreateDirectory("folder");

Asynchronous Programming

async / await

async Task GetDataAsync() {
  await Task.Delay(1000);
  return "data";
}

Task and Task<T>

Task t = Task.Run(() => Console.WriteLine("Running"));
Task t2 = Task.FromResult(42);

Parallel Programming (TPL)

Parallel.For(0, 10, i => Console.WriteLine(i));

CancellationToken

var cts = new CancellationTokenSource();
Task.Run(() => {
  while (!cts.Token.IsCancellationRequested) {
    Console.Write(".");
    Thread.Sleep(100);
  }
}, cts.Token);
cts.CancelAfter(500);

Language Features

var keyword

var count = 5; // inferred as int

dynamic type

dynamic obj = "Hello";
obj = 42;

object initializers

var person = new Person { Name = "Alice", Age = 30 };

using statement and declarations

using (var res = new StreamReader("file.txt")) {
  Console.WriteLine(res.ReadLine());
}

switch expressions

string category = age switch {
  < 13 => "Child",
  < 20 => "Teen",
  _ => "Adult"
};

record types

public record User(string Name, int Age);

target-typed new expressions

List numbers = new();

nullable value types

int? number = null;

.NET & Miscellaneous

Namespaces

namespace MyApp {
  class Program {}
}

Assemblies

Assemblies are compiled .NET code in DLL or EXE format.

Attributes

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

Reflection (basic)

Type type = typeof(string);
MethodInfo[] methods = type.GetMethods();

Dependency Injection (overview)

Use constructor injection and services registration with IServiceCollection in ASP.NET Core.

Unit Testing (overview)

Use xUnit, NUnit, or MSTest. Decorate test methods with [Fact] or [TestMethod].

Common .NET Libraries

  • System – Core types
  • System.Collections.Generic – Lists, Dictionaries
  • System.IO – File and stream handling
  • System.Threading.Tasks – async/await and tasks