Tags: web-dev reference

Reference - C Sharp

Language: C# 14 / .NET 10 (LTS, 10.0.14) — current stable. .NET 11 at RC3 (release candidate), due November 2026
Checked: 2026-10-30


C# is TypeScript’s syntax with Java’s runtime model: compiled ahead of time to an intermediate language, JIT-compiled on a managed runtime with a garbage collector, and typed for real — the types survive into the running program, so the compiler and the runtime both enforce them. Most surprises coming from JS are about that, plus value types and real threads.


§0 The one idea

C# compiles to IL, and the CLR runs it with the types still attached.

  • IL (Intermediate Language) — a CPU-independent bytecode, plus metadata describing every type, method and field. It’s what’s inside a .dll
  • CLR (Common Language Runtime) — the virtual machine that loads IL, JIT-compiles it (just-in-time — to machine code, per method, on first call), runs the garbage collector, and checks types at runtime — The Common Language Runtime
  • BCL (Base Class Library) — the large standard library: collections, I/O, HTTP, JSON, regex, dates, threading. Far more is built in than in Node
TYPESCRIPT + NODE                              C# + .NET

app.ts                                         Program.cs
  │ tsc — checks types, then ERASES them         │ Roslyn (the C# compiler) — checks types,
  ▼                                              ▼   KEEPS them as metadata
app.js            ← no types left              Shop.dll   IL + full type metadata
  │ node / V8 parses source text                 │ dotnet — the CLR loads the assembly
  ▼                                              ▼
V8 JIT → machine code                          JIT → machine code, per method
  one thread + event loop                        thread pool, real parallelism
  GC                                             GC

What to notice: both end at a JIT and a GC. The difference is what survives the build. TS types are a lint pass that disappears; C# types are part of the shipped binary.

vs TS: consequences of types existing at runtime —

  • A cast is checked. (Order)obj throws InvalidCastException if it isn’t one. TS’s obj as Order is a promise to the compiler that nothing verifies
  • Generics are real. List<int> and List<string> are different types at runtime; typeof(T) works inside a generic method
  • Reflection sees everything — the runtime can enumerate a type’s properties, which is how JSON serialisers, ORMs and DI containers work without you writing mapping code
  • Typing is nominal, not structural. Two classes with identical shapes are not interchangeable; a type satisfies an interface only by declaring it — Structural Typing, Type Systems

vs JS: Node has one thread running your code and an event loop — The Event Loop. .NET has a thread pool: many threads running your code at once. async/await looks the same but schedules onto those threads, so shared mutable state can genuinely race — Concurrency and Parallelism, Async in C#.


1. The .NET platform shape

You can’t run anything without this, and it’s the part a JS developer has least intuition for.

The pieces:

  • .NET — the platform: runtime + BCL + SDK. Formerly ”.NET Core”; the Windows-only ”.NET Framework” (4.x) is the legacy line, still in old enterprise code, and what most pre-2016 tutorials mean
  • Runtime — the CLR plus BCL. Enough to run a built app. What a server needs
  • SDK — runtime + compiler + dotnet CLI + MSBuild + NuGet client. What you need to build
  • dotnet CLI — one binary for everything: new, build, run, test, add packages, publish
  • MSBuild — the build engine. A .csproj is an MSBuild file
  • Assembly — the unit of deployment: a .dll containing IL and metadata. Each project builds one assembly
  • NuGet — the package manager and registry (nuget.org). Packages are zipped assemblies

Analogy table

Node / npm.NETDifference worth knowing
nodedotnetdotnet is runtime launcher and toolchain
npm / pnpmNuGet (via dotnet)No separate tool to install
package.json.csprojXML, and also holds build config (tsconfig’s job too)
package-lock.jsonpackages.lock.jsonOpt-in, not default
node_modules/~/.nuget/packages/Global per-user cache, shared by every project. Nothing in the repo
tsconfig.json target<TargetFramework>Which .NET version you compile against
npm workspaces / monorepo root.sln / .slnx solutionGroups projects; mostly an IDE and build convenience
npx tsx script.tsdotnet run app.csFile-based apps, .NET 10+ — see below
dist/bin/Plus obj/ for intermediate build state. Gitignore both

The CLI

dotnet new console -n Shop          # scaffold from a template
cd Shop
dotnet run                          # restore + build + run
dotnet build                        # → bin/Debug/net10.0/
dotnet add package Humanizer        # add a NuGet reference to the .csproj
dotnet test                         # run a test project
dotnet publish -c Release           # build for deployment → bin/Release/net10.0/publish/
dotnet new list                     # every installed template

dotnet add package and dotnet package add are equivalent — .NET 10 added noun-first forms of these commands; the old order still works. [CHECK: confirm both forms against dotnet --help on your installed SDK]

Restore is implicit. build, run and test all fetch packages first — there is no npm install step to forget.

A minimal project

Shop/
├── Shop.csproj           project file — the package.json equivalent
├── Program.cs            entry point (top-level statements)
├── obj/                  restore + intermediate output   ← gitignore
└── bin/
    └── Debug/
        └── net10.0/
            ├── Shop.dll                 YOUR CODE, as IL
            ├── Shop                     native launcher (Shop.exe on Windows)
            ├── Shop.runtimeconfig.json  which runtime version to load
            ├── Shop.deps.json           dependency manifest
            └── Shop.pdb                 debug symbols — source maps, roughly

What to notice: Shop.dll is not a Windows thing. It’s an assembly, cross-platform, and dotnet Shop.dll runs it on macOS or Linux.

The .csproj

<Project Sdk="Microsoft.NET.Sdk">
 
  <PropertyGroup>
    <OutputType>Exe</OutputType>                    <!-- Exe or (default) Library -->
    <TargetFramework>net10.0</TargetFramework>       <!-- the target framework moniker -->
    <ImplicitUsings>enable</ImplicitUsings>          <!-- common namespaces auto-imported -->
    <Nullable>enable</Nullable>                      <!-- nullable reference types on -->
  </PropertyGroup>
 
  <ItemGroup>
    <PackageReference Include="Humanizer" Version="2.14.1" />
  </ItemGroup>
 
</Project>

That is the whole file dotnet new console produces (minus the package). SDK-style — the Sdk="..." attribute pulls in sensible defaults, and every .cs file under the folder is compiled automatically; old-style csproj files listed every file by hand and ran to hundreds of lines.

  • Sdk — Microsoft.NET.Sdk for console/libraries, Microsoft.NET.Sdk.Web for web apps — Reference - ASP.NET Core
  • TargetFramework — a TFM (target framework moniker): net10.0, net8.0. A library can multi-target with <TargetFrameworks>net8.0;net10.0</TargetFrameworks> (note the plural)
  • The C# version follows the TFM. net10.0 gets C# 14 by default; no separate setting needed
  • ImplicitUsings — for a console app, auto-imports System, System.IO, System.Linq, System.Collections.Generic, System.Net.Http, System.Threading and System.Threading.Tasks

Solutions: .sln and .slnx

A solution groups several projects — typically an app, a class library, and a test project.

Shop.slnx
src/Shop.Web/Shop.Web.csproj          references ↓
src/Shop.Core/Shop.Core.csproj        domain code, no web dependency
tests/Shop.Core.Tests/...csproj       references Shop.Core
  • .slnx is the new XML format; dotnet new sln creates .slnx by default from .NET 10. Pass --format sln for the old one
  • .sln is the legacy format — GUID-laden, unreadable, merge-conflict-prone. Convert with dotnet sln Shop.sln migrate
  • A solution is optional. dotnet build works on a lone .csproj. You need one when there are several projects to build together
dotnet new sln -n Shop
dotnet sln add src/Shop.Core/Shop.Core.csproj
dotnet add src/Shop.Web reference src/Shop.Core     # project-to-project reference

File-based apps (.NET 10+)

A single .cs file runs without a project. The nearest thing to node script.js.

#!/usr/bin/env -S dotnet --
#:package Humanizer@2.14.1
 
using Humanizer;
 
Console.WriteLine(DateTime.UtcNow.AddHours(-3).Humanize());

dotnet run app.cs (or dotnet app.cs, or chmod +x and ./app.cs). #:package, #:sdk and #:property directives replace the .csproj; the SDK builds a hidden project and caches it. dotnet project convert app.cs promotes it to a real project when it outgrows one file. Publishing a file-based app defaults to native AOT (see below).

Releases: LTS and STS

.NET 8    LTS   Nov 2023   support ends 10 Nov 2026   ← ending in days
.NET 9    STS   Nov 2024   support ends 10 Nov 2026   ← same day
.NET 10   LTS   Nov 2025   support ends 14 Nov 2028   ← current; build on this
.NET 11   STS   RC3 at time of writing — GA expected Nov 2026

new major version every November
even = LTS (Long Term Support)      3 years
odd  = STS (Standard Term Support)  2 years
  • Same quality either way — the difference is only support length. Most production code sits on LTS and jumps two versions at a time
  • Patches are cumulative and monthly (Patch Tuesday) — “supported” means “on the latest patch”
  • C# versions ship in lockstep: C# 12 ↔ .NET 8, C# 13 ↔ .NET 9, C# 14 ↔ .NET 10. [CHECK: C# 15 ships with .NET 11 — confirm its feature list at GA before writing about it]

How it runs, and the alternatives to JIT

  • Default — JIT, tiered. Methods are first compiled quickly with few optimisations, then recompiled optimised once they prove hot. Startup is fast-ish; peak speed arrives after warm-up — the same shape as V8
  • ReadyToRun — pre-compiles IL to native code at publish, keeping IL as a fallback. Faster startup, bigger files
  • Native AOT (ahead-of-time) — compiles everything to a single native executable, no JIT, no runtime install needed. Fast startup, small memory. Costs: reflection-heavy code (some serialisers, some ORMs) may not work, because AOT can’t see what you’ll reflect over

2. The smallest working form

Console.WriteLine("Hello");

That’s a complete Program.cs. No class, no Main, no using (implicit usings supply System). This is top-level statements — the compiler wraps the file in a generated Main method.

The explicit form is equivalent — what every pre-2021 tutorial shows, and what the compiler generates behind the one-liner:

namespace Shop;
 
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Hello");
    }
}
  • Only one file per project may use top-level statements — it’s the entry point
  • args is still available in top-level code, as an implicit string[]
  • await works at top level — the generated Main becomes async Task Main
  • return 1; at top level sets the exit code
  • Type declarations go after the statements in the same file, or in other files

Semicolons are mandatory. No automatic insertion.


3. Variables, var, and the type split

int count = 3;
decimal price = 19.99m;      // m suffix = decimal literal
double ratio = 0.5;
bool paid = true;
char initial = 'A';          // single quotes = char, a different type from string
string name = "Serum";       // double quotes = string
 
var total = price * count;   // inferred: decimal. Fixed forever
const int MaxItems = 50;     // compile-time constant

var is inference, not dynamic typing. total is a decimal from that line on; total = "x" is a compile error. vs TS: same as let total = price * count in TS. Locals only — fields, parameters and return types must be written out.

var orders = new List<Order>();           // type on the right
List<Order> orders = new();               // type on the left — target-typed new
List<Order> orders = [];                  // collection expression (C# 12)

These three are equivalent. House style picks one; var is the most common for locals.

Value types and reference types — the big one

Every C# type is one or the other, and it decides what = does.

Value typesReference types
Examplesint double decimal bool char DateTime Guid, every struct, every enumevery class, string, arrays, record (class), delegates, interfaces
The variable holdsthe data itselfa pointer to an object on the heap
b = acopies the datacopies the pointer — both see one object
Default valuezero (0, false, '\0')null
Can be null?Only as int? (Nullable<int>)Yes — the compiler warns, see §8
== by defaultcompares contentscompares identity (string and records override this)
struct PointS { public int X; }          // value type
class  PointC { public int X; }          // reference type
 
var a = new PointS { X = 1 };
var b = a;            // COPY
b.X = 99;
Console.WriteLine(a.X);   // 1   ← a untouched
 
var c = new PointC { X = 1 };
var d = c;            // same object
d.X = 99;
Console.WriteLine(c.X);   // 99  ← c changed

vs JS: JS has the same split but you can’t choose it — primitives copy, objects share. In C# you choose per type: struct gets copy semantics, class gets JS-object semantics. Use class by default; struct is for small, immutable, value-like things (a coordinate, a money amount) where avoiding a heap allocation matters — Memory Models.

Boxing — putting a value type where an object is expected (object o = 42;) copies it into a heap allocation. Invisible in the syntax, costs an allocation, and the boxed copy is detached from the original.

Enums

enum Status { Draft, Paid, Cancelled }      // 0, 1, 2
 
var s = Status.Paid;
int n = (int)s;                // 1
var weird = (Status)42;        // LEGAL — no runtime check

Enums are named integers, nothing more — any int casts in without complaint. vs TS: closer to a TS numeric enum than to a string union. Validate with Enum.IsDefined when the value comes from outside.

Numbers

Console.WriteLine(7 / 2);          // 3      ← int ÷ int = int, truncated
Console.WriteLine(7 / 2.0);        // 3.5
Console.WriteLine(0.1 + 0.2 == 0.3);     // False  (double)
Console.WriteLine(0.1m + 0.2m == 0.3m);  // True   (decimal)

vs JS: JS has one number (a double). C# has int (32-bit), long (64-bit), double, float, decimal and more, and integer arithmetic stays integer. Integer overflow wraps silently by default (int.MaxValue + 1 is negative); wrap a block in checked { } to throw instead.

decimal for money, always. It’s base-10, so 0.10 is stored exactly; double is base-2 and can’t represent it. Slower, and it’s the correct choice for any price, VAT or total.


4. Strings

var name = "Serum";
var price = 19.99m;
 
var a = "Product: " + name;                    // concatenation
var b = $"Product: {name} at {price:C}";       // interpolation, with a format specifier
var c = @"C:\shop\orders";                     // verbatim — backslashes are literal
var d = """
    { "name": "Serum" }
    """;                                       // raw string literal (C# 11) — no escaping
var e = $$"""{ "name": "{{name}}" }""";        // raw + interpolation: $$ means {{ }} interpolates

$"..." is the template literal. vs JS: `Product: ${name}` becomes $"Product: {name}" — prefix instead of backticks, no $ inside. The :C after the colon is a format specifier (currency); :N2, :P0, :yyyy-MM-dd and so on.

  • Strings are immutable reference types that compare by value — == on two strings compares characters, unlike other classes
  • Build long strings with StringBuilder, not += in a loop
  • Comparison and casing are culture-sensitive by default. Be explicit: string.Equals(a, b, StringComparison.OrdinalIgnoreCase)

Formatting follows the server’s culture. price.ToString("C") prints £19.99 on a UK machine and $19.99 on a US-configured container. Pin it where it matters:

using System.Globalization;
 
var gb = CultureInfo.GetCultureInfo("en-GB");
Console.WriteLine(19.99m.ToString("C", gb));     // £19.99

5. Methods

static decimal Gross(decimal net, decimal vat = 0.20m)
{
    return net * (1 + vat);
}
 
static decimal Gross2(decimal net, decimal vat = 0.20m) => net * (1 + vat);   // expression-bodied
 
Console.WriteLine(Gross(50m));                  // 60.00
Console.WriteLine(Gross(50m, 0.05m));           // 52.50
Console.WriteLine(Gross(vat: 0.05m, net: 50m)); // named arguments, any order

The two forms are equivalent — => expr is a body of one return.

  • Return type comes first, before the name. void for nothing
  • Overloading is real — two methods can share a name if their parameters differ. vs TS: TS overloads are signatures over one implementation; C# overloads are separate methods
  • params for variadic: static int Sum(params int[] n) => n.Sum();
// out — a second return value, used by every TryXxx method
if (int.TryParse("42", out var qty))
    Console.WriteLine(qty * 2);     // 84
 
// tuples — the usual way to return several values
static (decimal Net, decimal Vat) Split(decimal gross) => (gross / 1.2m, gross - gross / 1.2m);
 
var (net, vat) = Split(120m);       // deconstruction — 100, 20

TryParse is the idiom where JS would return NaN or throw: it returns bool, and the value comes back through out. ref passes a variable by reference so the method can reassign it — rare in application code.


6. Classes, properties, constructors

The smallest class

var o = new Order();
o.Id = "A1";
Console.WriteLine(o.Id);
 
class Order
{
    public string Id { get; set; } = "";
}

{ get; set; } is an auto-property — the compiler generates a hidden field and two accessor methods. vs JS: looks like a field, is actually a getter/setter pair. Public fields exist but are unidiomatic; properties are the norm because you can add logic later without changing callers.

Property variations, one at a time

class Product
{
    public string Sku { get; }                       // read-only: set only in constructor
    public string Name { get; init; } = "";          // settable only during object creation
    public required decimal Price { get; set; }      // must be set by the caller (C# 11)
    public int Stock { get; private set; }           // public read, private write
    public bool InStock => Stock > 0;                // computed, no storage
 
    public string Slug                               // `field` keyword (C# 14)
    {
        get;
        set => field = value.Trim().ToLowerInvariant();
    } = "";
 
    public Product(string sku) => Sku = sku;
}
 
var p = new Product("SER-01") { Name = "Serum", Price = 19.99m };   // object initialiser
// p.Name = "x";    ← compile error: init-only
  • init — immutable after construction, but set with initialiser syntax rather than constructor arguments
  • required — compile error if the caller’s initialiser omits it. vs TS: the nearest thing to a non-optional property in an object literal
  • field (C# 14) — refers to the compiler’s hidden backing field, so you can add logic to one accessor without declaring the field yourself

Constructors

class Basket
{
    private readonly List<string> _items;            // readonly field: assign once
 
    public Basket() : this(new List<string>()) { }   // chain to another constructor
 
    public Basket(List<string> items)
    {
        _items = items;
    }
 
    public int Count => _items.Count;
}

Primary constructors (C# 12)

class OrderService(IOrderRepository repo, ILogger log)
{
    public Order Find(string id)
    {
        log.Log($"Finding {id}");
        return repo.Get(id);
    }
}

Parameters on the class name are in scope for the whole class body. The standard shape for a service that receives its dependencies — Dependency Injection.

They are not properties. new OrderService(r, l).repo doesn’t compile — the parameters are captured privately, and they’re mutable. On a record (next section) the same syntax does create public properties. That asymmetry is the trap.

this is always the instance. vs JS: no bind, no arrow-function workaround, no lost this when passing a method as a callback — this and Binding.


7. Records

record Order(string Id, decimal Total);
 
var a = new Order("A1", 60m);
var b = new Order("A1", 60m);
 
Console.WriteLine(a == b);           // True   ← value equality
Console.WriteLine(a);                // Order { Id = A1, Total = 60 }
 
var c = a with { Total = 72m };      // non-destructive copy
Console.WriteLine(a.Total);          // 60     ← a unchanged

A record is a class the compiler finishes for you — public init properties from the parameter list, value-based == and GetHashCode, a readable ToString, deconstruction, and with.

vs JS: { ...a, total: 72 } is the with expression. And a == b comparing contents is what JS developers always wanted from === on objects — Immutability.

  • record = record class — reference type with value equality
  • record struct — value type with the same conveniences
  • Use records for data: DTOs (data transfer objects — the shapes that cross an API boundary), messages, results, anything compared by content. Classes for things with identity and behaviour
  • Value equality is shallow. A record holding a List<T> compares the list by reference

8. Nullable reference types

With <Nullable>enable</Nullable> (the template default since .NET 6):

string  name  = "Serum";     // never null — compiler enforces
string? maybe = null;        // may be null
 
Console.WriteLine(maybe.Length);     // ⚠ warning CS8602: possible null dereference
Console.WriteLine(maybe?.Length);    // null-conditional: null if maybe is null
Console.WriteLine(maybe ?? "none");  // null-coalescing
Console.WriteLine(maybe!.Length);    // ! = "trust me" — silences the warning, can still throw
 
if (maybe is not null)
    Console.WriteLine(maybe.Length); // fine — flow analysis narrowed it
 
customer?.Address = "x";             // null-conditional assignment (C# 14)

vs TS: this is strictNullChecks, nearly symbol for symbol — ?, ?., ??, ! and control-flow narrowing all behave the same — Type Narrowing.

And like TS, it’s compile-time only. The one exception to §0: string? and string are the same type at runtime. The annotations are warnings, not errors — null still gets in through deserialisation, reflection, old libraries, or !. Turn on <TreatWarningsAsErrors>true</TreatWarningsAsErrors> (or just for nullable: <WarningsAsErrors>nullable</WarningsAsErrors>) to make them stick.

int? is different. On a value type, ? creates a real runtime type, Nullable<int>, with .HasValue and .Value. Same punctuation, two mechanisms.


9. Interfaces and inheritance

interface IPayable
{
    decimal Amount { get; }
    string Describe() => $"£{Amount}";       // default implementation (C# 8)
}
 
abstract class Payment : IPayable
{
    public abstract decimal Amount { get; }
    public virtual string Method => "unknown";   // overridable
}
 
sealed class CardPayment(decimal amount) : Payment
{
    public override decimal Amount => amount;
    public override string Method => "card";
}
 
IPayable p = new CardPayment(25m);
Console.WriteLine(p.Describe());      // £25
  • One base class, many interfaces. class X : Base, IA, IB — the base class must come first
  • Interface names start with I — convention, followed universally
  • Methods are non-virtual by default. Only virtual or abstract members can be overridden, and the override says override. vs JS: every method on a prototype can be replaced — Prototypes and Inheritance
  • sealed — no subclasses. Sealing by default is a reasonable habit
  • abstract — can’t be instantiated; abstract members must be implemented

vs TS: implementing an interface is a declaration, not a shape match. A class with the right members that doesn’t say : IPayable is not an IPayable — Structural Typing.


10. Generics

static T First<T>(List<T> items) => items[0];
 
class Box<T>(T value)
{
    public T Value { get; } = value;
}
 
static T Max<T>(T a, T b) where T : IComparable<T>      // constraint
    => a.CompareTo(b) >= 0 ? a : b;
 
Console.WriteLine(First(new List<int> { 3, 1 }));   // 3 — T inferred
Console.WriteLine(Max("apple", "pear"));            // pear
Console.WriteLine(typeof(Box<int>) == typeof(Box<string>));   // False

Syntax is TypeScript’s, constraints use where instead of extends — Generics.

vs TS: generics are reified — kept at runtime. Box<int> is a distinct type, typeof(T) works inside the method, and a List<int> stores raw ints without boxing. TS generics vanish on compile, which is why you can’t write new T() or check x instanceof T there.

Common constraints: where T : class (reference type), struct (value type), notnull, new() (has a parameterless constructor), SomeBase, ISomeInterface.


11. Collections

int[] fixedSize = [1, 2, 3];                  // array: fixed length
var list = new List<string> { "a", "b" };     // growable — the JS array equivalent
list.Add("c");
 
var stock = new Dictionary<string, int>
{
    ["SER-01"] = 12,
    ["CRM-02"] = 0,
};
 
var tags = new HashSet<string> { "new", "sale" };
 
Console.WriteLine(list.Count);                 // 3  — Count, not length
Console.WriteLine(fixedSize.Length);           // 3  — arrays use Length
Console.WriteLine(stock["SER-01"]);            // 12
// stock["NOPE"]                               ← throws KeyNotFoundException
if (stock.TryGetValue("NOPE", out var qty)) { }  // the safe read
JSC#Note
ArrayList<T>T[] is fixed-length
MapDictionary<TKey,TValue>Missing key throws, doesn’t return undefined
SetHashSet<T>
arr.lengthlist.Count / array.LengthInconsistent, historically
Object.freeze(arr)IReadOnlyList<T>, ImmutableList<T>Read-only interface vs truly immutable

Expose interfaces, not concrete types. A method returning IReadOnlyList<Order> or IEnumerable<Order> lets you change the implementation; returning List<Order> hands the caller a mutable list.

IEnumerable<T> is the root interface — “something you can foreach over”. Every collection implements it, and LINQ is built on it.

Spans, briefly

ReadOnlySpan<char> sku = "SER-01-RED".AsSpan();
ReadOnlySpan<char> colour = sku[7..];          // "RED" — no new string allocated

Span<T> / ReadOnlySpan<T> is a window onto existing memory — slicing without copying. Used heavily inside the BCL for parsing performance. You’ll mostly meet it in method signatures. Limit: a span can only live on the stack, so it can’t be a class field or cross an await.


12. LINQ

LINQ (Language Integrated Query) — a set of extension methods on IEnumerable<T> that do what .map/.filter/.reduce do in JS, plus grouping, joining, ordering and set operations — LINQ.

var orders = new List<Order>
{
    new("A1", 60m, "paid"),
    new("A2", 15m, "draft"),
    new("A3", 90m, "paid"),
};
 
var paidTotal = orders
    .Where(o => o.Status == "paid")       // filter
    .Select(o => o.Total)                 // map
    .Sum();                               // 150
 
record Order(string Id, decimal Total, string Status);
JSLINQ
.filter.Where
.map.Select
.flatMap.SelectMany
.reduce.Aggregate (or .Sum, .Count, .Average, .Max)
.find.FirstOrDefault (null/default if none) · .First (throws if none)
.some / .every.Any / .All
.sort (mutates).OrderBy / .ThenBy (returns new sequence)
Object.groupBy.GroupBy
.slice.Skip / .Take
—.Distinct, .Join, .Zip, .Chunk

Query syntax is equivalent — the compiler rewrites it to the method calls:

var bigPaid =
    from o in orders
    where o.Status == "paid" && o.Total > 50m
    orderby o.Total descending
    select o.Id;
 
var bigPaid2 = orders
    .Where(o => o.Status == "paid" && o.Total > 50m)
    .OrderByDescending(o => o.Total)
    .Select(o => o.Id);

Method syntax is far more common; query syntax reads better for joins.

Deferred execution

A LINQ query is a recipe, not a result. Nothing runs until something enumerates it — a foreach, .ToList(), .Count(), .First(). vs JS: .filter runs immediately and returns a new array. LINQ is lazy like a generator pipeline — Iterators and Generators.

var q = orders.Where(o => o.Total > 50m);        DEFINED — nothing has run

orders.Add(new("A4", 200m, "paid"));             source changes after definition

q.Count()   → 3    A1, A3, A4                    ← A4 included: query ran NOW
q.Count()   → 3    runs the whole filter AGAIN   ← second full pass
q.ToList()  → materialised once; stable from here

What to notice: the query sees data added after it was written, and every enumeration repeats the work. .ToList() when you want a snapshot or will read it more than once.

On a database the same syntax becomes SQL. EF Core’s (Entity Framework Core, .NET’s standard ORM) IQueryable<T> translates the lambda into a query rather than running it in memory — that’s Reference - ASP.NET Core territory, and it’s why calling .ToList() too early pulls a whole table into memory.


13. Pattern matching and switch expressions

static string Describe(object x) => x switch
{
    null                          => "nothing",
    int n when n < 0              => "negative int",          // type pattern + guard
    int n                         => $"int {n}",
    decimal and > 1000m           => "big money",             // type + relational pattern
    Order { Status: "paid" } o    => $"paid order {o.Id}",    // property pattern
    int[] and [var first, .., var last] => $"{first}…{last}", // list pattern (C# 11)
    _                             => "something else",        // discard = default
};

switch expressions are an expression returning a value, with no break, no fall-through and a compiler warning if the cases aren’t exhaustive. A non-exhaustive one that hits no case throws at runtime.

// is — test and bind in one step
if (payment is CardPayment { Amount: > 100m } card)
    Console.WriteLine($"Large card payment: {card.Amount}");
 
// tuple patterns — a decision table
var shipping = (country, total) switch
{
    ("GB", >= 50m) => 0m,
    ("GB", _)      => 3.95m,
    (_, _)         => 12m,
};

vs TS: the job TS does with discriminated unions and narrowing, done by the runtime against real types. No switch(true) hacks. vs JS: no equivalent in the language — pattern matching is still only a TC39 proposal. The old statement switch (with case/break) still exists; use the expression form for anything returning a value.


14. Exceptions

try
{
    var qty = int.Parse(input);
}
catch (FormatException ex)                          // most specific first
{
    Console.WriteLine($"Not a number: {ex.Message}");
}
catch (Exception ex) when (ex is not OutOfMemoryException)   // exception filter
{
    Log(ex);
    throw;                                          // rethrow, stack trace intact
}
finally
{
    Console.WriteLine("always runs");
}
  • Everything thrown derives from System.Exception. vs JS: you can’t throw "a string"
  • throw; not throw ex; — the bare form preserves the original stack trace; throw ex; resets it to this line
  • when filters decide whether to catch without unwinding the stack first — useful for logging without catching
  • No checked exceptions — unlike Java, signatures don’t declare what they throw
  • Exceptions are for exceptional cases. Expected failure uses TryXxx or a result type — Error Handling Strategies

using and IDisposable

using var file = File.OpenText("orders.csv");      // disposed at end of scope
Console.WriteLine(file.ReadLine());
 
using (var conn = OpenConnection())                // block form — equivalent
{
    // ...
}                                                  // conn.Dispose() called here, even on throw

The GC frees memory, not resources. File handles, sockets and database connections implement IDisposable; using guarantees Dispose() runs — compiled to try/finally. vs JS: the same idea as the newer using declaration and Symbol.dispose in JS, which C# has had since 2002 — Garbage Collection.


15. async, await and Task

using System.Net.Http;
 
var http = new HttpClient();
 
async Task<int> GetLengthAsync(string url)
{
    string body = await http.GetStringAsync(url);
    return body.Length;
}
 
int len = await GetLengthAsync("https://example.com");
Console.WriteLine(len);

Task<T> is Promise<T>. async marks a method that can await; the return type is Task (nothing) or Task<T> (a value). Methods are suffixed Async by convention.

JSC#
Promise<T>Task<T>
Promise<void>Task
Promise.allTask.WhenAll
Promise.raceTask.WhenAny
Promise.resolve(x)Task.FromResult(x)
setTimeout promiseTask.Delay(ms)
AbortSignalCancellationToken — passed as a parameter, everywhere
—ValueTask<T> — avoids an allocation when the result is often synchronous

Where it differs

vs JS: in Node, one thread runs all your code and await yields to the event loop. In .NET, await releases the thread back to the thread pool; when the I/O completes, the rest of the method resumes on whichever pool thread is free — possibly a different one, possibly at the same time as other code.

NODE                                     .NET

thread 1: A ── await ─┐                  pool thread 3: A ── await ─┐
thread 1: B runs      │                  pool thread 3: (free — other work)
thread 1: C runs      │                  pool thread 5: B runs  ┐ genuinely
thread 1: A resumes ◀─┘                  pool thread 7: C runs  ┘ simultaneous
                                         pool thread 5: A resumes ◀─┘
only one thing runs at a time            several things run at once

Consequence: code between two awaits is not atomic in .NET. Shared mutable state needs a lock, Interlocked, or a concurrent collection (ConcurrentDictionary<K,V>) — Race Conditions, Async Models.

var counter = 0;
await Task.WhenAll(Enumerable.Range(0, 1000).Select(_ => Task.Run(() => counter++)));
Console.WriteLine(counter);      // often < 1000 — lost updates
 
var safe = 0;
await Task.WhenAll(Enumerable.Range(0, 1000).Select(_ => Task.Run(() => Interlocked.Increment(ref safe))));
Console.WriteLine(safe);         // 1000
  • Task.Run pushes CPU-bound work onto a pool thread — real parallelism, which JS only gets via workers
  • Never block on a task — .Result and .Wait() hold a thread hostage until the task finishes. Under load that starves the pool; in UI apps and old ASP.NET it deadlocks. Async all the way up
  • ConfigureAwait(false) tells the continuation not to return to the original synchronisation context (a UI thread, or classic ASP.NET’s request context). ASP.NET Core and console apps have no such context, so in application code it does nothing. Library code still uses it because it can’t know where it’ll be called from
  • Pass CancellationTokens through — every async BCL method accepts one, and an abandoned web request should stop its database query

async void

async void Bad()   { await Task.Delay(1); throw new Exception("x"); }   // ✗
async Task Good()  { await Task.Delay(1); throw new Exception("x"); }   // ✓

async void can’t be awaited, and an exception inside it crashes the process — there’s no Task to carry the error back. vs JS: like an unhandled promise rejection with --unhandled-rejections=strict, but always. The only legitimate use is event handlers whose signature demands void.


16. Delegates, lambdas and events

Func<decimal, decimal> addVat = net => net * 1.2m;      // takes decimal, returns decimal
Action<string> log = msg => Console.WriteLine(msg);     // returns nothing
Predicate<int> isEven = n => n % 2 == 0;                // returns bool
 
Console.WriteLine(addVat(50m));     // 60.0
log("hi");

A delegate is a typed function reference. Func<…, TResult> (last type parameter is the return), Action<…> (void) cover almost everything; custom delegate types exist but are rare.

vs JS: functions are already values in JS; C# needed a type for them. The lambda syntax is the same arrow. Closures capture variables, not values — same as JS, and the same loop gotcha applies to for (but not foreach, which gets a fresh variable each iteration) — Closures.

static string Apply(Func<string, string> f, string s) => f(s);
 
Console.WriteLine(Apply(s => s.ToUpper(), "serum"));    // lambda
Console.WriteLine(Apply(Slug, "Night Serum"));          // method group — equivalent
 
static string Slug(string s) => s.ToLower().Replace(' ', '-');

Events

var basket = new Basket();
basket.ItemAdded += (sender, sku) => Console.WriteLine($"Added {sku}");   // subscribe
basket.Add("SER-01");
 
class Basket
{
    public event EventHandler<string>? ItemAdded;                          // declare
 
    public void Add(string sku) => ItemAdded?.Invoke(this, sku);           // raise
}

event is a delegate field that outsiders can only += and -=, never invoke or overwrite. vs JS: addEventListener/removeEventListener, built into the language. Same leak as the DOM: a subscriber stays alive as long as the publisher holds the handler — unsubscribe with -=.


17. Namespaces, using and access modifiers

namespace Shop.Orders;                 // file-scoped namespace (C# 10) — whole file
 
using System.Text.Json;                // import a namespace (usings conventionally go first)
using Money = System.Decimal;          // alias
 
public class OrderService { }

Namespaces are not modules. vs JS: an ES module is a file and imports name specific exports. A C# namespace is a naming prefix that can span many files and assemblies; using Shop.Orders; brings every public type in it into scope. What you can reference is decided by project and package references in the .csproj, not by import paths — Modules.

  • Block-scoped form is equivalent: namespace Shop.Orders { ... } — older style, an extra indent level
  • global using System.Text.Json; in any one file applies to the whole project — what ImplicitUsings generates
  • Convention: namespace mirrors folder path — src/Shop/Orders/OrderService.cs → Shop.Orders. Not enforced
ModifierVisible toDefault for
publicanyone—
internalsame assembly (project) onlytop-level types
protectedthis class and subclasses—
privatethis class onlymembers
protected internalsubclasses or same assembly—
private protectedsubclasses in the same assembly—
file (C# 11)this source file—

vs TS: TS private is compile-time only and #private is runtime. C# access modifiers are enforced by the runtime too (reflection can get round them, deliberately). internal has no TS equivalent — it’s “public within this package”, and it’s how libraries hide implementation.


18. Attributes

using System.Text.Json;
using System.Text.Json.Serialization;
 
var json = JsonSerializer.Serialize(new Product("SER-01", 19.99m, "internal note"));
Console.WriteLine(json);    // {"sku":"SER-01","price":19.99}
 
record Product(
    [property: JsonPropertyName("sku")]   string Sku,
    [property: JsonPropertyName("price")] decimal Price,
    [property: JsonIgnore]                string Notes);
 
class Legacy
{
    [Obsolete("Use NewMethod")]
    public void OldMethod() { }       // callers get a compiler warning
}

An attribute is passive metadata attached to a type, member or parameter. It does nothing on its own — something else reads it: the serialiser via reflection, the compiler ([Obsolete]), a test runner ([Fact]), a web framework ([HttpGet], [Authorize]), or a source generator (a compiler plug-in that writes extra C# at build time).

vs TS: decorators look identical and are the opposite. A TS decorator is a function that runs at definition time and can replace what it decorates. A C# attribute is inert data the runtime stores alongside the type.


19. Extension methods and extension members

var slug = "Night Serum".ToSlug();           // looks like a string method
Console.WriteLine(slug);                     // night-serum
 
static class StringExtensions
{
    public static string ToSlug(this string s)          // `this` on the first parameter
        => s.Trim().ToLowerInvariant().Replace(' ', '-');
}

A static method the compiler lets you call as if it were an instance method. It’s in scope wherever its namespace is using-ed. It can’t access private members — it’s sugar over StringExtensions.ToSlug("Night Serum"), which is equivalent and also valid.

This is how LINQ works. .Where and .Select aren’t methods on List<T>; they’re extension methods on IEnumerable<T> in System.Linq. vs JS: like monkey-patching String.prototype, without the patching — nothing is modified, it’s resolved at compile time, and two libraries can’t collide globally.

Extension members (C# 14) — a new extension block that can also add properties and static members:

Console.WriteLine("".IsBlank);               // True — extension property
Console.WriteLine(string.Slugify("A B"));    // a-b  — static extension member
 
static class StringExtensions
{
    extension(string s)                      // instance members for string
    {
        public bool IsBlank => string.IsNullOrWhiteSpace(s);
    }
 
    extension(string)                        // static members for string
    {
        public static string Slugify(string s) => s.Trim().ToLowerInvariant().Replace(' ', '-');
    }
}

The classic this syntax still works and is equivalent for methods; the block form is needed only for properties, static members and operators.


Equivalent forms

// entry point
Console.WriteLine("x");                                   // top-level statements
static void Main(string[] args) { Console.WriteLine("x"); }   // explicit, inside a class
 
// object creation
var list = new List<int>();
List<int> list = new();
List<int> list = [];
 
// method body
int Double(int n) { return n * 2; }
int Double(int n) => n * 2;
 
// namespace
namespace Shop;                    // file-scoped
namespace Shop { }                 // block-scoped
 
// LINQ
from o in orders where o.Paid select o.Id
orders.Where(o => o.Paid).Select(o => o.Id)
 
// extension method call
"x".ToSlug()
StringExtensions.ToSlug("x")
 
// disposal
using var f = Open();              // to end of scope
using (var f = Open()) { }         // to end of block
 
// NOT equivalent
string? s      // compile-time annotation only
int? n         // real runtime type, Nullable<int>
 
record R(int X);   // X is a public init property
class  C(int X);   // X is a private captured parameter

Required versus optional

ThingRequired?
A .csprojYes for a project. No for a single-file app (dotnet run app.cs, .NET 10+)
A .sln/.slnxNo — only when building several projects together
A Main methodNo — top-level statements in one file replace it
A class around everythingNo in the entry file; yes for every method elsewhere (all other code lives in a type)
A namespace in every fileNo, but convention and every template use one
using System;No with ImplicitUsings on (the default)
SemicolonsYes
Type annotations on localsNo — var
Type annotations on fields, parameters, returnsYes
Access modifiersNo — defaults are private (members) and internal (types). Write them anyway
Freeing memoryNo — the GC does it
Disposing files, connections, socketsYes — using
async on a method returning TaskNo — only if it uses await inside
nullAllowed on reference types, warned if not declared ? with nullable on. Not allowed on value types unless T?
A constructorNo — a parameterless one is generated if you write none
override when overridingYes — and the base member must be virtual or abstract
ConfigureAwait(false)No in app code; yes by convention in libraries
Declaring exceptions a method throwsNo — C# has no checked exceptions

Where it bites

Value-type copying. A struct in a List<T> comes out as a copy:

var points = new List<PointS> { new() { X = 1 } };
// points[0].X = 5;          ← compile error CS1612: the indexer returns a copy
var p = points[0]; p.X = 5; points[0] = p;     // read, modify, write back
 
struct PointS { public int X; }

The compiler catches this case. It doesn’t catch a struct passed to a method that mutates its parameter — the caller’s copy silently stays the same.

== is chosen at compile time.

string a = "serum", b = new string("serum".ToCharArray());
Console.WriteLine(a == b);              // True  — string's == compares characters
 
object oa = a, ob = b;
Console.WriteLine(oa == ob);            // False — object's == compares references
Console.WriteLine(oa.Equals(ob));       // True  — Equals is virtual, dispatches at runtime

Same values, different answer, because the declared type picks the operator. Classes compare by reference unless they override; records and strings compare by value. vs JS: === on objects is always identity — Equality and Coercion.

Nullable warnings ignored. They are warnings. A codebase with 400 of them has no null safety at all. Treat as errors from day one, and treat every ! as a claim needing a reason.

async void — crashes the process on exception and can’t be awaited. async Task instead, everywhere except event handlers.

Blocking on async — .Result, .Wait(), .GetAwaiter().GetResult() in a web app consumes a pool thread for the whole wait. Fine at ten requests, pool starvation at a thousand.

LINQ re-running. A query stored in a variable runs every time it’s enumerated:

var expensive = orders.Where(o => CallSlowApi(o));   // nothing yet
if (expensive.Any())                                  // runs — stops at first match
    foreach (var o in expensive) { }                  // runs AGAIN, from the start
var once = expensive.ToList();                        // run once, keep the result

IEnumerable<T> multiple enumeration. The general form of the above. A method taking IEnumerable<T> may be handed a lazy query, a database cursor or a generator that can only be read once. Enumerate it once — .ToList() at the top if you need it twice. IDEs flag this.

decimal vs double for money. double for measurements, decimal for money. Mixing them needs an explicit cast, which is the compiler stopping you — don’t silence it by switching everything to double.

decimal price = 19.99m;
double  rate  = 0.2;
// var vat = price * rate;              ← compile error: decimal * double
var vat = price * (decimal)rate;        // explicit — and 0.2 as a double isn't exactly 0.2
var vat2 = price * 0.2m;                // better: decimal from the start

Integer division — total / count with two ints truncates. (decimal)total / count.

Culture-dependent formatting and parsing — decimal.Parse("19,99") succeeds on a German-culture server and fails on a UK one. Pass CultureInfo.InvariantCulture for machine-readable data.

Enum values from outside — (Status)42 is legal and silent. Validate.

DateTime kinds — a DateTime carries a Kind (Utc, Local, Unspecified) that most code ignores. Use DateTimeOffset for timestamps, or DateTime.UtcNow consistently.


The kitchen sink

Labelled as such — not how to write a class. Every feature above, coexisting, so the syntax is recognisable when met in real code:

namespace Shop.Orders;
 
using System.Text.Json.Serialization;
 
public interface IOrderRepository
{
    Task<Order?> FindAsync(string id, CancellationToken ct = default);
}
 
public enum Status { Draft, Paid, Cancelled }
 
public sealed record OrderLine(string Sku, int Qty, decimal UnitPrice)
{
    public decimal Total => Qty * UnitPrice;
}
 
public sealed class Order(string id, IReadOnlyList<OrderLine> lines) : IComparable<Order>
{
    [JsonPropertyName("id")]
    public string Id { get; } = id;
    public required Status Status { get; init; }
    public DateTimeOffset? PlacedAt { get; init; }
    public IReadOnlyList<OrderLine> Lines { get; } = lines;
 
    public string? Note
    {
        get;
        set => field = value?.Trim();
    }
 
    public decimal Total => Lines.Sum(l => l.Total);
 
    public string Label => (Status, Total) switch
    {
        (Status.Draft, _)          => "Not yet placed",
        (Status.Paid, >= 100m)     => "Paid — free delivery",
        (Status.Paid, _)           => "Paid",
        (Status.Cancelled, _)      => "Cancelled",
        _                          => throw new InvalidOperationException(),
    };
 
    public event EventHandler<Status>? StatusChanged;
 
    public int CompareTo(Order? other) => Total.CompareTo(other?.Total ?? 0m);
 
    public override string ToString() => $"{Id}: {Total:C} ({Label})";
}
 
public static class OrderExtensions
{
    public static decimal VatAt(this Order o, decimal rate = 0.20m) => o.Total - o.Total / (1 + rate);
}
 
public sealed class OrderService(IOrderRepository repo)
{
    public async Task<string> DescribeAsync(string id, CancellationToken ct = default)
    {
        var order = await repo.FindAsync(id, ct).ConfigureAwait(false);
        return order is { Status: Status.Paid } paid
            ? $"{paid} — VAT {paid.VatAt():C}"
            : "Not found or unpaid";
    }
}

A complete program, top to bottom

A console app: one Shop.csproj as in §1, and this as Program.cs. dotnet run prints a VAT summary by status.

using System.Globalization;
 
var gb = CultureInfo.GetCultureInfo("en-GB");
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
 
IOrderSource source = new FakeOrderSource();
var orders = await source.LoadAsync(cts.Token);
 
// LINQ: group, project, materialise once
var summary = orders
    .Where(o => o.Status != Status.Cancelled)
    .GroupBy(o => o.Status)
    .Select(g => new StatusTotal(g.Key, g.Count(), g.Sum(o => o.Gross)))
    .OrderByDescending(s => s.Gross)
    .ToList();
 
foreach (var s in summary)
{
    var net = s.Gross / (1 + Vat.Standard);
    Console.WriteLine(string.Create(gb,
        $"{s.Status,-8} {s.Count,3} orders  gross {s.Gross,10:C}  VAT {s.Gross - net,9:C}"));
}
 
var largest = orders.MaxBy(o => o.Gross);
Console.WriteLine(largest is null ? "No orders" : $"Largest: {largest.Id}");
 
return summary.Count == 0 ? 1 : 0;      // exit code
 
 
// ── types: after the top-level statements ──────────────────────
 
enum Status { Draft, Paid, Refunded, Cancelled }
 
record Order(string Id, Status Status, decimal Gross);
 
record StatusTotal(Status Status, int Count, decimal Gross);
 
static class Vat
{
    public const decimal Standard = 0.20m;
}
 
interface IOrderSource
{
    Task<IReadOnlyList<Order>> LoadAsync(CancellationToken ct);
}
 
sealed class FakeOrderSource : IOrderSource
{
    public async Task<IReadOnlyList<Order>> LoadAsync(CancellationToken ct)
    {
        await Task.Delay(100, ct);          // stands in for an HTTP or database call
        return
        [
            new("A1", Status.Paid,      60.00m),
            new("A2", Status.Draft,     15.00m),
            new("A3", Status.Paid,     120.00m),
            new("A4", Status.Refunded,  30.00m),
            new("A5", Status.Cancelled, 45.00m),
        ];
    }
}

What to notice: money is decimal end to end; formatting is pinned to en-GB so £ doesn’t depend on the server; the query is .ToList()-ed once before being enumerated; the async load takes a cancellation token; the types sit below the top-level code, where the compiler requires them.


Beyond the language

  • Web apps, hosting, the dependency-injection container, middleware, EF Core (Entity Framework Core, the ORM — object-relational mapper) — Reference - ASP.NET Core. Constructor injection is just a constructor taking interfaces (§6); the container that fills them in lives there — Dependency Injection
  • A CMS on top of it — Reference - Umbraco
  • Testing — xUnit, NUnit and MSTest are the three frameworks; dotnet new xunit scaffolds a test project