Outsourced IT Partner
Support ยท systems ยท strategy
ยฉ 2026
One person, one business โ IT support here, websites at webology.online.
One person, one business โ IT support here, websites at webology.online.
๐ท C# Programming Language
Quick Reference & Cheat Sheet - .NET Framework, Syntax & Standard Library
Basic Syntax
Program Structure
using System;
using System.Collections.Generic;
using System.Linq;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
}
}
}
// Top-level programs (C# 9.0+)
using System;
Console.WriteLine("Hello, World!");
Data Types
// Value types
bool flag = true;
byte b = 255;
char letter = 'A';
int number = 42;
long bigNumber = 1234567890L;
float decimal = 3.14f;
double precision = 3.14159;
decimal money = 99.99m;
// Reference types
string text = "Hello World";
object obj = new object();
int[] array = {1, 2, 3, 4, 5};
// Nullable types
int? nullableInt = null;
string? nullableString = null; // C# 8.0+
// var keyword (implicit typing)
var name = "John"; // string
var age = 30; // int
var list = new List(); // List
Constants & Variables
// Constants
const int MAX_SIZE = 100;
const string APP_NAME = "MyApp";
// Read-only fields
readonly DateTime createdDate = DateTime.Now;
// Static variables
static int instanceCount = 0;
// Properties
public string Name { get; set; }
public int Age { get; private set; }
public string FullName => $"{FirstName} {LastName}";
// Auto-implemented properties
public string FirstName { get; set; } = "Default";
Control Structures
Conditionals
// If statement
if (condition)
{
// code
}
else if (anotherCondition)
{
// code
}
else
{
// code
}
// Ternary operator
string result = condition ? "true" : "false";
// Switch statement
switch (value)
{
case 1:
// code
break;
case 2:
case 3:
// code for 2 or 3
break;
default:
// default code
break;
}
// Switch expression (C# 8.0+)
string dayType = day switch
{
DayOfWeek.Monday or DayOfWeek.Tuesday => "Weekday",
DayOfWeek.Saturday or DayOfWeek.Sunday => "Weekend",
_ => "Unknown"
};
Loops
// For loop
for (int i = 0; i < 10; i++)
{
Console.WriteLine(i);
}
// Foreach loop
int[] numbers = {1, 2, 3, 4, 5};
foreach (int num in numbers)
{
Console.WriteLine(num);
}
// While loop
while (condition)
{
// code
}
// Do-while loop
do
{
// code
} while (condition);
// Break and continue
break; // exit loop
continue; // skip to next iteration
Methods & Functions
Method Declaration
// Basic method
public int Add(int a, int b)
{
return a + b;
}
// Method with default parameters
public void Greet(string name, string greeting = "Hello")
{
Console.WriteLine($"{greeting}, {name}!");
}
// Method overloading
public int Add(int a, int b) => a + b;
public double Add(double a, double b) => a + b;
public string Add(string a, string b) => a + b;
// Static method
public static double CalculateArea(double radius)
{
return Math.PI * radius * radius;
}
// Extension method
public static class StringExtensions
{
public static bool IsValidEmail(this string email)
{
return email.Contains("@");
}
}
// Usage: "test@example.com".IsValidEmail();
Lambda Expressions & Delegates
// Lambda expressions
Func add = (x, y) => x + y;
Action print = message => Console.WriteLine(message);
Predicate isEven = x => x % 2 == 0;
// Delegates
public delegate void MyDelegate(string message);
MyDelegate del = Console.WriteLine;
del += message => File.WriteAllText("log.txt", message);
// Events
public event Action OnMessageReceived;
OnMessageReceived?.Invoke("Hello");
// Anonymous methods
Button.Click += delegate(object sender, EventArgs e)
{
MessageBox.Show("Button clicked!");
};
Collections
Generic Collections
List<T>
Dictionary<TKey, TValue>
HashSet<T>
Queue<T>
Stack<T>
LinkedList<T>
SortedList<TKey, TValue>
SortedDictionary<TKey, TValue>
// List
var list = new List {"apple", "banana", "cherry"};
list.Add("date");
list.Remove("banana");
list.Insert(1, "blueberry");
// Dictionary
var dict = new Dictionary
{
{"apple", 5},
{"banana", 3}
};
dict["cherry"] = 7;
dict.TryGetValue("apple", out int value);
// HashSet
var set = new HashSet {1, 2, 3, 3, 4}; // {1, 2, 3, 4}
set.Add(5);
bool contains = set.Contains(3);
// Queue and Stack
var queue = new Queue();
queue.Enqueue("first");
string first = queue.Dequeue();
var stack = new Stack();
stack.Push(1);
int top = stack.Pop();
Classes & Objects
Class Definition
public class Person
{
// Fields
private string _name;
private int _age;
// Properties
public string Name
{
get => _name;
set => _name = value ?? throw new ArgumentNullException();
}
public int Age { get; set; }
// Auto-implemented property
public string Email { get; set; }
// Constructors
public Person() : this("Unknown", 0) { }
public Person(string name, int age)
{
Name = name;
Age = age;
}
// Methods
public virtual void Introduce()
{
Console.WriteLine($"Hi, I'm {Name} and I'm {Age} years old.");
}
// Static method
public static Person CreateAdult(string name)
{
return new Person(name, 18);
}
// Override ToString
public override string ToString()
{
return $"Person: {Name}, Age: {Age}";
}
}
Inheritance & Interfaces
// Interface
public interface IDrawable
{
void Draw();
string Color { get; set; }
}
// Abstract class
public abstract class Shape : IDrawable
{
public string Color { get; set; }
public abstract double Area { get; }
public abstract void Draw();
public virtual void Move(int x, int y)
{
Console.WriteLine($"Moving shape to ({x}, {y})");
}
}
// Inheritance
public class Circle : Shape
{
public double Radius { get; set; }
public override double Area => Math.PI * Radius * Radius;
public override void Draw()
{
Console.WriteLine($"Drawing a {Color} circle with radius {Radius}");
}
// Method hiding
public new void Move(int x, int y)
{
Console.WriteLine($"Moving circle to ({x}, {y})");
}
}
LINQ
LINQ Methods
Where(predicate)
Select(selector)
OrderBy(keySelector)
OrderByDescending(keySelector)
GroupBy(keySelector)
Join(inner, outerKey, innerKey, result)
First() / FirstOrDefault()
Last() / LastOrDefault()
Single() / SingleOrDefault()
Any(predicate)
All(predicate)
Count() / Count(predicate)
Sum() / Average() / Min() / Max()
Take(count) / Skip(count)
Distinct()
ToList() / ToArray()
var numbers = new[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// Method syntax
var evenNumbers = numbers
.Where(n => n % 2 == 0)
.Select(n => n * n)
.OrderByDescending(n => n)
.ToList();
// Query syntax
var evenSquares = from n in numbers
where n % 2 == 0
orderby n descending
select n * n;
// Complex LINQ
var people = new List();
var adults = people
.Where(p => p.Age >= 18)
.GroupBy(p => p.Age)
.Select(g => new { Age = g.Key, Count = g.Count() })
.OrderBy(x => x.Age);
Exception Handling
Try-Catch-Finally
// Basic exception handling
try
{
int result = 10 / 0;
}
catch (DivideByZeroException ex)
{
Console.WriteLine($"Division by zero: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"General exception: {ex.Message}");
}
finally
{
Console.WriteLine("This always executes");
}
// Using statement (automatic disposal)
using (var file = new FileStream("file.txt", FileMode.Open))
{
// File is automatically closed when leaving this block
}
// Using declaration (C# 8.0+)
using var file = new FileStream("file.txt", FileMode.Open);
// File is automatically closed at end of scope
// Custom exceptions
public class CustomException : Exception
{
public CustomException(string message) : base(message) { }
public CustomException(string message, Exception innerException)
: base(message, innerException) { }
}
Modern C# Features
C# 6.0+ Features
// String interpolation (C# 6.0)
string name = "John";
int age = 30;
string message = $"Hello, {name}! You are {age} years old.";
// Null-conditional operators (C# 6.0)
string? text = null;
int? length = text?.Length;
string result = text ?? "default";
// Expression-bodied members (C# 6.0)
public string FullName => $"{FirstName} {LastName}";
public void PrintName() => Console.WriteLine(FullName);
// Pattern matching (C# 7.0+)
if (obj is string str)
{
Console.WriteLine($"String: {str}");
}
switch (obj)
{
case int i when i > 0:
Console.WriteLine($"Positive integer: {i}");
break;
case string s:
Console.WriteLine($"String: {s}");
break;
case null:
Console.WriteLine("Null value");
break;
}
// Tuples (C# 7.0)
(string name, int age) person = ("John", 30);
var (name2, age2) = person;
// Local functions (C# 7.0)
int Add(int x, int y)
{
return x + y;
int Multiply(int a, int b) => a * b; // Local function
}
// Records (C# 9.0)
public record Person(string Name, int Age);
var person1 = new Person("John", 30);
var person2 = person1 with { Age = 31 };