
C# Cheatsheet
19 of 19 code examples
Hello World
Basic program
Basicsusing System;
class Program
{
static void Main()
{
Console.WriteLine("Hello World");
}
}
Variables
Variable declarations
Basicsstring name = "John";
int age = 30;
double price = 19.99;
bool isActive = true;
// Type inference
var city = "New York";
var score = 95.5;
// Constants
const double PI = 3.14159;
Control Flow
If, loops, switch
Basics// If statement
if (age >= 18)
{
Console.WriteLine("Adult");
}
// For loop
for (int i = 0; i < 10; i++)
{
Console.WriteLine(i);
}
// Foreach
foreach (var item in items)
{
Console.WriteLine(item);
}
// Switch
switch (day)
{
case "Monday":
Console.WriteLine("Start week");
break;
default:
Console.WriteLine("Other day");
break;
}
Methods
Function definitions
Functions// Basic method
void Greet(string name)
{
Console.WriteLine($"Hello {name}");
}
// Return value
int Add(int a, int b)
{
return a + b;
}
// Optional parameters
void Print(string text, bool uppercase = false)
{
Console.WriteLine(uppercase ? text.ToUpper() : text);
}
Classes
Class definition
OOPclass Person
{
// Properties
public string Name { get; set; }
public int Age { get; set; }
// Constructor
public Person(string name, int age)
{
Name = name;
Age = age;
}
// Method
public void Introduce()
{
Console.WriteLine($"I'm {Name}, {Age} years old");
}
}
// Usage
var person = new Person("Alice", 25);
person.Introduce();
Inheritance
Class inheritance
OOPclass Animal
{
public void Eat()
{
Console.WriteLine("Eating...");
}
}
class Dog : Animal
{
public void Bark()
{
Console.WriteLine("Woof!");
}
}
// Usage
var dog = new Dog();
dog.Eat();
dog.Bark();
Interfaces
Interface implementation
OOPinterface IShape
{
double CalculateArea();
}
class Circle : IShape
{
public double Radius { get; set; }
public double CalculateArea()
{
return Math.PI * Radius * Radius;
}
}
// Usage
IShape circle = new Circle { Radius = 5 };
Console.WriteLine(circle.CalculateArea());
Collections
Lists and dictionaries
Data Structures// List
List<string> names = new List<string> { "Alice", "Bob" };
names.Add("Charlie");
// Dictionary
Dictionary<string, int> ages = new Dictionary<string, int>();
ages["Alice"] = 30;
ages["Bob"] = 25;
// LINQ
var adults = names.Where(n => ages[n] >= 18)
.OrderBy(n => n)
.ToList();
Exception Handling
Try-catch blocks
Error Handlingtry
{
int result = 10 / int.Parse("0");
}
catch (DivideByZeroException ex)
{
Console.WriteLine("Cannot divide by zero");
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
finally
{
Console.WriteLine("Cleanup");
}
Async/Await
Asynchronous programming
Advancedasync Task<string> DownloadDataAsync()
{
using var client = new HttpClient();
return await client.GetStringAsync("https://api.example.com/data");
}
// Usage
async Task ProcessDataAsync()
{
var data = await DownloadDataAsync();
Console.WriteLine(data);
}
Properties
Property accessors
OOPclass User
{
// Auto property
public string Name { get; set; }
// Read-only
public DateTime Created { get; } = DateTime.Now;
// Computed
public bool IsAdult => Age >= 18;
// With validation
private int age;
public int Age
{
get => age;
set => age = value >= 0 ? value : 0;
}
}
Generics
Generic types
Advancedclass Repository<T>
{
private List<T> items = new List<T>();
public void Add(T item)
{
items.Add(item);
}
public T Get(int index)
{
return items[index];
}
}
// Usage
var repo = new Repository<string>();
repo.Add("Hello");
Delegates
Function pointers
Advanced// Delegate
public delegate void MessageHandler(string message);
// Usage
void ProcessMessage(string msg)
{
Console.WriteLine(msg);
}
MessageHandler handler = ProcessMessage;
handler("Hello!");
// Lambda
Action<string> print = msg => Console.WriteLine(msg);
Func<int, int, int> add = (a, b) => a + b;
Extension Methods
Adding methods to types
Advancedstatic class StringExtensions
{
public static bool IsEmpty(this string str)
{
return string.IsNullOrEmpty(str);
}
}
// Usage
string text = "";
Console.WriteLine(text.IsEmpty()); // True
Records
Immutable data types
Advanced// Record definition
public record Person(string Name, int Age);
// Usage
var person1 = new Person("John", 30);
var person2 = person1 with { Age = 31 };
// Value equality
Console.WriteLine(person1 == new Person("John", 30)); // True
Pattern Matching
Modern switch statements
Advancedstring GetTypeDescription(object obj) => obj switch
{
string s => $"String: {s}",
int i => $"Integer: {i}",
null => "Null",
_ => "Unknown"
};
// Usage
Console.WriteLine(GetTypeDescription("hello"));
File I/O
Reading and writing files
I/O// Read file
string content = File.ReadAllText("file.txt");
// Write file
File.WriteAllText("output.txt", "Hello World");
// Read lines
string[] lines = File.ReadAllLines("data.csv");
JSON
JSON serialization
Data Formatsvar person = new { Name = "John", Age = 30 };
// Serialize
string json = JsonSerializer.Serialize(person);
// Deserialize
var deserialized = JsonSerializer.Deserialize<Person>(json);
Web API Controller
ASP.NET Core controller
Web[ApiController]
[Route("api/[controller]")]
public class UsersController : ControllerBase
{
[HttpGet]
public IActionResult GetUsers()
{
var users = new[] { "Alice", "Bob" };
return Ok(users);
}
[HttpGet("{id}")]
public IActionResult GetUser(int id)
{
var user = new { Id = id, Name = "John" };
return Ok(user);
}
}