C# Cheatsheet
C# is a modern, strongly typed language commonly used with .NET for apps, APIs, and tools.
Focus on classes/records, nullability, and async/await—they appear throughout real projects.
Full lessons: C# Tutorials
Basics
Hello world
Top-level statements keep small programs short; larger apps use namespaces and classes.
Console.WriteLine("Hello");
Variables
Declare with explicit types or var when the type is obvious.
int count = 0;
var name = "Ada";
String interpolation
Embed expressions in strings with $"...".
Console.WriteLine($"Hi, {name}");
Nullable reference types
With nullable enabled, string? may be null; plain string should not.
string? maybe = null;
string sure = maybe ?? "default";
dotnet CLI
Create, run, and test projects with the .NET SDK.
dotnet new console -n Hello
cd Hello
dotnet run
Types & OOP
Class
Reference type with fields, properties, and methods.
public class User {
public int Id { get; set; }
public string Name { get; set; } = "";
}
Record
Immutable-friendly type with value-like equality—great for DTOs.
public record Book(string Title, int Year);
Interface
Contract of members a type must implement.
public interface ILogger {
void Log(string message);
}
Inheritance
Derive with :. Prefer composition when inheritance is unclear.
public class Admin : User { }
Collections & LINQ
List
Dynamic array of items.
var nums = new List<int> { 1, 2, 3 };
nums.Add(4);
Dictionary
Key/value lookups.
var ages = new Dictionary<string, int> { ["Ada"] = 36 };
LINQ Where / Select
Query collections declaratively.
var evens = nums.Where(n => n % 2 == 0).ToList();
var names = users.Select(u => u.Name);
FirstOrDefault
Safely get one item or a default when missing.
var user = users.FirstOrDefault(u => u.Id == 1);
Async & errors
async / await
Write asynchronous code that reads like synchronous code.
public async Task<string> LoadAsync() {
return await File.ReadAllTextAsync("a.txt");
}
Task
Represents an asynchronous operation. Prefer returning Task/Task<T> from async methods.
await Task.Delay(100);
try / catch
Handle exceptions; be specific when possible.
try {
// work
} catch (FileNotFoundException ex) {
Console.WriteLine(ex.Message);
}
using
Dispose resources automatically.
using var reader = new StreamReader("a.txt");
var text = reader.ReadToEnd();
Comments
One comment per signed-in account. Comments are saved with this page’s URL.