C#
Table of Contents
General-purpose, statically-typed, object-oriented language developed by Microsoft in 2000. Runs on the .NET platform — compiled to CIL (Common Intermediate Language), executed by the CLR (Common Language Runtime). Multi-paradigm: OOP at core, with strong functional features (LINQ, lambda, async/await).
Primary domains: web (ASP.NET Core), game development (Unity), Windows desktop, enterprise, and cloud (Azure).
Related: Object Oriented Programming SOLID Principles Type System Functional Programming DLL
Syntax Quick Reference
// Variables and types int count = 10; string name = "Alice"; bool active = true; var inferred = 42; // type inferred at compile time int? nullable = null; // nullable value type // String interpolation Console.WriteLine($"Hello, {name}! Count: {count}"); // Collections var list = new List<string> { "a", "b", "c" }; var dict = new Dictionary<string, int> { ["one"] = 1, ["two"] = 2 }; // Control flow if (count > 5) Console.WriteLine("big"); else Console.WriteLine("small"); for (int i = 0; i < 10; i++) { } foreach (var item in list) { } while (count > 0) { count--; } // Switch expression (modern) string result = count switch { > 10 => "large", > 5 => "medium", _ => "small" };
Classes and OOP
public class User { // Properties (auto-implemented) public int Id { get; set; } public string Name { get; private set; } public bool Active { get; init; } // init-only (C# 9) // Constructor public User(int id, string name, bool active = true) { Id = id; Name = name ?? throw new ArgumentNullException(nameof(name)); Active = active; } // Method public string Greet() => $"Hello, I am {Name}"; // Override public override string ToString() => $"User({Id}, {Name})"; } // Inheritance public class AdminUser : User { public string Role { get; set; } = "admin"; public AdminUser(int id, string name) : base(id, name) { } } // Record (immutable, value semantics — C# 9) public record Point(int X, int Y); var p1 = new Point(1, 2); var p2 = p1 with { Y = 5 }; // non-destructive mutation
Interfaces and Generics
public interface IRepository<T> { T GetById(int id); IEnumerable<T> GetAll(); void Save(T entity); } public class UserRepository : IRepository<User> { private readonly List<User> _users = new(); public User GetById(int id) => _users.FirstOrDefault(u => u.Id == id) ?? throw new KeyNotFoundException(); public IEnumerable<User> GetAll() => _users.AsReadOnly(); public void Save(User entity) => _users.Add(entity); }
LINQ
Language-Integrated Query — query collections with SQL-like syntax or fluent method chaining.
var users = new List<User> { new(1, "Alice"), new(2, "Bob"), new(3, "Alice") }; // Method syntax (most common) var activeAlices = users .Where(u => u.Active && u.Name == "Alice") .OrderBy(u => u.Id) .Select(u => u.Name) .ToList(); // Query syntax var result = from u in users where u.Active orderby u.Id select u.Name; // Aggregation int count = users.Count(u => u.Active); var grouped = users.GroupBy(u => u.Name); var first = users.FirstOrDefault(u => u.Id == 1); // ToList(), ToArray(), ToDictionary() materialise the query var byId = users.ToDictionary(u => u.Id, u => u.Name);
Async / Await
public async Task<string> FetchDataAsync(string url) { using var client = new HttpClient(); var response = await client.GetAsync(url); response.EnsureSuccessStatusCode(); return await response.Content.ReadAsStringAsync(); } // Call async from async public async Task RunAsync() { string data = await FetchDataAsync("https://api.example.com/data"); Console.WriteLine(data); } // Run from synchronous context string result = FetchDataAsync("https://api.example.com").GetAwaiter().GetResult(); // Parallel async var tasks = urls.Select(u => FetchDataAsync(u)); var results = await Task.WhenAll(tasks);
Exception Handling
try { var result = int.Parse("not a number"); } catch (FormatException ex) { Console.WriteLine($"Parse error: {ex.Message}"); } catch (Exception ex) when (ex.Message.Contains("specific")) { // Exception filter — C# 6 } finally { // Always runs — cleanup } // Custom exception public class DomainException : Exception { public DomainException(string message) : base(message) { } }
Null Safety
// Null conditional operator string? name = user?.Name; // null if user is null int length = user?.Name?.Length ?? 0; // Null coalescing string display = name ?? "Unknown"; // Null coalescing assignment name ??= "Default"; // Non-nullable reference types (C# 8 with nullable enabled) // string name = null; ← compiler warning // string? name = null; ← explicit nullable
The .NET Ecosystem
| Component | Purpose |
|---|---|
| CLR | Executes CIL, manages memory via GC |
| BCL | Base Class Library — standard types and APIs |
| ASP.NET Core | Web framework — APIs and web apps |
| Entity Framework Core | ORM for database access |
| MSBuild / dotnet CLI | Build, test, publish |
| NuGet | Package manager |
# CLI commands dotnet new console -n MyApp dotnet new webapi -n MyApi dotnet run dotnet test dotnet build dotnet add package Newtonsoft.Json dotnet publish -c Release -r linux-x64 --self-contained
Security Relevance
C# appears frequently in Windows security tooling — both offensive and defensive. Understanding C# is useful for reading and writing:
- Offensive: Cobalt Strike payloads, SharpHound, SharpUp, Rubeus, SafetyKatz, many LOLBIN-adjacent tools are C#
- Defensive: EDR and SIEM connectors, Windows service wrappers, custom Sysmon parsers
- Webshells:
.aspxwebshells are C# executed server-side on IIS
// Minimal ASPX webshell (see File Upload note) // <%@ Page Language="C#" %> // System.Diagnostics.Process.Start(cmd)
Tips
vardoes not mean dynamic — the type is still inferred at compile time and is fully static- Prefer
recordtypes for DTOs and value objects — immutability and value equality come for free async voidis almost always wrong except for event handlers — useasync Taskso exceptions can be caught and awaited- LINQ is lazy by default — call
.ToList()or.ToArray()to force evaluation when you need all results immediately - Nullable reference types (
<Nullable>enable</Nullable>) are worth enabling on new projects — the compiler warns on most null dereference bugs before they happen at runtime