C# · Lesson 1

C# basics for TypeScript developers

How a .NET project is organised, value and reference types, numbers (int, long, double, decimal), strings and formatting, static methods, control flow, arrays, const and readonly, and switch expressions, each next to the TypeScript you already know.

18 min read

In short

  • Methods live in types: a static class is your module
  • var is inference, not any
  • int / int truncates; decimal (19.99m) is for money
  • Value types copy, reference types share
  • No truthiness: conditions must be a bool
  • Switch expressions: first match wins, end with _

C# and TypeScript were both designed by Anders Hejlsberg, and it shows: classes, generics, lambdas, async/await, ?. and ?? all look familiar. The big differences are underneath. C# is compiled to .NET bytecode (IL) at build time, its types are real at runtime (no erasure), numbers come in several sizes, and there is no any escape hatch hiding in the corners. This lesson gets you reading and writing everyday C#, the kind you'll find in an ASP.NET Core API or a background worker on day one.

Most C# snippets below have a ▶ Try button. Predict the output first, then run it. The first C# run builds a small project and takes about 10 seconds. After that, runs take a second or two.

How a .NET project is organised

A TypeScript project has package.json and tsconfig.json. A C# project has one file that does both jobs, the .csproj:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net10.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Dapper" Version="2.1.35" />
  </ItemGroup>
</Project>
  • TargetFramework is the runtime version, like target/lib in tsconfig.json. .NET 10 is the current LTS release. The lab compiles your code as C# 12 so it also runs on a .NET 8 SDK.
  • Nullable turns on nullable reference types: string can't be null, string? can. It is the strictNullChecks of C#, and every modern codebase has it on.
  • ImplicitUsings imports common namespaces (System, System.Linq, System.Collections.Generic, System.Threading.Tasks...) into every file, so you don't write them at the top.
  • PackageReference is a NuGet package, like a dependency in package.json. There is no node_modules folder: packages live in a shared cache.
  • Unlike tsconfig's include, you don't list source files. Every .cs file under the folder is compiled.

The dotnet command line is your npm:

dotnet new console -n Billing      # new project: Billing/Billing.csproj + Program.cs
dotnet new webapi -n Billing.Api   # an ASP.NET Core API
dotnet new xunit -n Billing.Tests  # a test project
dotnet run                         # build and run (like npm start)
dotnet build                       # compile; output goes to bin/ (obj/ holds intermediate files)
dotnet test                        # run the tests
dotnet add package Dapper
dotnet add reference ../Billing/Billing.csproj

A real repository groups several projects in a solution (.sln, or the newer XML .slnx), which is what Visual Studio and Rider open. A typical layout on a .NET team:

Example.Billing.sln
Directory.Build.props              settings shared by every project (Nullable, LangVersion, analyzers)
src/Example.Billing.Api/           ASP.NET Core: controllers or minimal APIs, Program.cs
src/Example.Billing.Domain/        class library: your types and business rules
tests/Example.Billing.Tests/       xUnit tests

Program.cs, namespaces and using

Program.cs is the entry point. Modern C# lets it start with plain statements (top-level statements), like a TypeScript file that just runs. The compiler wraps them in a hidden Main method.

// Program.cs (not runnable here: the lab's snippets are a single file)
using Example.Billing.Domain;      // like an import, but of a whole namespace

var invoice = new Invoice("INV-1", 120.50m);
Console.WriteLine(invoice.Number);
// Domain/Invoice.cs (not runnable here)
namespace Example.Billing.Domain;  // file-scoped namespace: everything below belongs to it

public class Invoice(string number, decimal total)
{
    public string Number { get; } = number;
    public decimal Total { get; } = total;
}

The differences from TypeScript modules:

  • A namespace groups types by name, not by file. Many files contribute to one namespace, and by convention the folder path matches it (Domain/Invoice.cs holds Example.Billing.Domain.Invoice).
  • using Example.Billing.Domain; brings every type in that namespace into scope. You never import a single file or a single function. global using X; in one file applies to the whole project.
  • Visibility replaces export. public types are visible to other projects. internal (the default for a top-level type) means "only inside this project". Members of a class are private by default.
  • There are no free functions. Every method lives in a type. Where TypeScript has a module of exported functions, C# has a static class.

How your code runs in this lab

Each exercise is one file that declares types only: a public static class with methods, a record, a class. The tests are a second file of top-level statements that calls your code, xUnit-style:

// Your file: types only (not runnable here on its own, there are no statements to run)
public static class Pricing
{
    public static decimal Double(decimal amount) => amount * 2;
}
// The tests (not runnable here: they need the lab's test harness)
Test("doubles", () => Assert.Equal(5.00m, Pricing.Double(2.50m)));

The first block above has no top-level statements, so on its own it has nothing to run. Lesson snippets do the opposite: statements first, then any types they need at the bottom.

Values and types

▶ Try
int count = 3;                 // 32-bit integer
long bytes = 5_000_000_000L;   // 64-bit integer; _ separates digits
double ratio = 0.75;           // 64-bit floating point, like a JS number
decimal price = 19.99m;        // base-10 decimal: exact for money
bool active = true;
char grade = 'A';              // one UTF-16 character, single quotes
string name = "Ada";           // text, double quotes

var total = price * count;     // inferred as decimal
Console.WriteLine($"{name} owes {total} ({total.GetType().Name})");
▶ Try
const count = 3;
const bytes = 5_000_000_000; // every number is a double in JS
const price = 19.99;
const total = price * count;
console.log(`total is ${total}`); // 59.97 (by luck: floating point)
C#SizeLiteralUse it for
int32-bit42counts, indexes, ids. The default integer.
long64-bit42Lbig counts, file sizes, Unix milliseconds
double64-bit float4.2, 4.2dmeasurements, maths, ratios. Same as a JS number.
float32-bit float4.2fgraphics and ML APIs that ask for it
decimal128-bit base-104.2mmoney, anything a human adds up on paper
booltrueno truthiness: conditions must be bool
char16-bit'x'a single character
stringreference"x"text (immutable, like JS strings)

var is inference, not any

var asks the compiler to infer the type from the right-hand side, like let x = 3 in TypeScript (a var can be reassigned). The type is fixed from then on:

▶ Try
var answer = 42;          // int
// answer = "forty-two";  // error CS0029: cannot convert string to int
// var nothing;           // error CS0818: var needs an initializer
var names = new List<string> { "Ada", "Grace" };
List<string> others = new();   // target-typed new: the type on the left tells `new()` what to build
Console.WriteLine($"{answer} {names.Count} {others.Count}");

Teams differ on style. A common rule is "use var when the type is obvious from the right-hand side".

Integers are not doubles

In TypeScript every number is a double. In C# the types of the operands decide the arithmetic:

▶ Try
Console.WriteLine(7 / 2);        // 3: int / int is integer division (truncates)
Console.WriteLine(7 / 2.0);      // 3.5: one double makes it double division
Console.WriteLine(7 % 2);        // 1
Console.WriteLine((double)7 / 2);// 3.5: cast before dividing, not after
Console.WriteLine((int)3.99);    // 3: casting to int truncates toward zero
Console.WriteLine((int)-3.99);   // -3

Integer division is the number one bug for people coming from JavaScript. percent / 100 with an int percent is 0 for anything under 100. Write percent / 100m (or 100.0) to get a fraction.

Integers also overflow silently by default:

▶ Try
int requests = int.MaxValue;   // 2,147,483,647
requests++;
Console.WriteLine(requests);   // -2147483648: it wrapped around

try
{
    int big = int.MaxValue;
    checked { big++; }         // checked arithmetic throws instead
}
catch (OverflowException e)
{
    Console.WriteLine(e.GetType().Name);
}

Use long for anything that can pass about two billion: bytes, ticks, row counts in a big table.

decimal for money

double stores binary fractions, so 0.1 is not exactly 0.1. That's fine for physics and terrible for invoices. decimal stores base-10 digits, so what you type is what you get:

▶ Try
Console.WriteLine(0.1 + 0.2);            // 0.30000000000000004
Console.WriteLine(0.1m + 0.2m);          // 0.3
Console.WriteLine(0.1 + 0.2 == 0.3);     // False
Console.WriteLine(0.1m + 0.2m == 0.3m);  // True

decimal net = 10.50m;
decimal gross = net * 1.17m;             // 12.2850
Console.WriteLine(Math.Round(gross, 2));                                // 12.28 (banker's rounding)
Console.WriteLine(Math.Round(gross, 2, MidpointRounding.AwayFromZero)); // 12.29 (what invoices expect)

Four things to remember:

  • The m suffix is required. decimal d = 19.99; doesn't compile, because 19.99 is a double and C# won't silently convert it.
  • Math.Round rounds halves to the nearest even digit by default ("banker's rounding"). Say MidpointRounding.AwayFromZero when the business rule says "round half up".
  • Mixing decimal and double needs an explicit cast. That's the compiler stopping a precision bug. In SQL Server and EF Core, decimal(18,2) columns map to decimal.
  • A decimal remembers its trailing zeros: 2.5m * 1.20m is 3.000m, and it prints that way. The value still equals 3m (== ignores the scale). Format with F2 or N2 when you display it.

Converting and parsing

▶ Try
long big = 42;                 // int to long: implicit, no data can be lost
int small = (int)big;          // long to int: explicit cast, you accept the risk
double d = small;              // int to double: implicit

int port = int.Parse("8080");                  // throws FormatException on bad input
if (int.TryParse("80a", out int parsed))       // the TryParse pattern: no exception
    Console.WriteLine($"parsed {parsed}");
else
    Console.WriteLine("not a number");

Console.WriteLine(decimal.Parse("19.99") + 0.01m);
Console.WriteLine(port + 1);

TryParse returns a bool and hands the value back through an out parameter. You'll see the pattern everywhere in .NET (Dictionary.TryGetValue, Guid.TryParse, Enum.TryParse). Use Parse when bad input is a bug, and TryParse when bad input is expected (user input, query strings, files).

Value types and reference types

This is the biggest new idea. Every C# type is one of two kinds:

  • Value types (int, double, decimal, bool, char, DateTime, Guid, enums and structs) hold their data directly. Assigning or passing one copies it.
  • Reference types (string, arrays, List<T>, classes, records other than record struct) live on the heap. A variable holds a reference, and assigning copies the reference, so both variables see the same object. This is how every JavaScript object behaves.
▶ Try
int a = 1;
int b = a;          // copy of the value
b++;
Console.WriteLine($"a={a} b={b}");                 // a=1 b=2

int[] xs = [1, 2, 3];
int[] ys = xs;      // copy of the reference: same array
ys[0] = 99;
Console.WriteLine($"xs[0]={xs[0]}");               // 99

Value types can't be null unless you ask with ?: int? maybeCount = null;. Reference types can hold null at runtime, and nullable reference types (string vs string?) make the compiler warn you when you might be passing one where it isn't allowed. The Classes & records topic covers struct vs class in depth.

string is a reference type that behaves like a value: it is immutable, and == compares the characters, not the references. So "ab" + "c" == "abc" is true, just like in JavaScript.

Strings and formatting

▶ Try
string name = "Ada";
decimal balance = 1234.5m;
int days = 7;

Console.WriteLine($"Hi {name}, you owe {balance:N2} due in {days} days");
Console.WriteLine($"[{name,8}] [{name,-8}]");      // right- and left-align in 8 characters
Console.WriteLine($"{days:D3} {0.5:F3} {255:X}");  // zero-pad, fixed decimals, hex
Console.WriteLine($"{{braces}} need doubling");

string path = @"C:\temp\new";                      // verbatim: backslashes are literal
string json = """
    { "name": "Ada", "active": true }
    """;                                           // raw string literal: no escaping at all
Console.WriteLine(path);
Console.WriteLine(json);
  • $"..." is a template literal. Inside the braces, ,8 sets a width (negative means left-aligned) and :N2 is a format string: N2 (thousands separators, 2 decimals), F2 (2 decimals), D3 (pad an integer to 3 digits), X (hex), and date formats such as {when:yyyy-MM-dd}.
  • Formatting follows the current culture. On a server, 1234.5 with N2 is 1,234.50 in en-US and 1.234,50 in de-DE. For machine-readable output (logs, CSV, JSON, URLs) format with CultureInfo.InvariantCulture. The lab runs with the invariant culture, which formats like en-US.
  • Strings are immutable. Building one in a loop with += copies it every time. Use StringBuilder or string.Join for big or repeated concatenation.
  • Compare text with an explicit rule: string.Equals(a, b, StringComparison.OrdinalIgnoreCase). ToLower() comparisons allocate and are culture-sensitive.

Handy members you'll use daily: Length, Trim(), Split(','), Contains, StartsWith, Replace, Substring, ToUpperInvariant(), PadLeft(5, '0'), string.IsNullOrWhiteSpace(s), string.Join(", ", items).

Methods and static classes

▶ Try
Console.WriteLine(Shipping.Cost(2.5m));                 // 7.990
Console.WriteLine(Shipping.Cost(2.5m, express: true));  // 17.990
var (min, max) = Shipping.Range([3, 9, 1]);
Console.WriteLine($"{min}..{max}");

public static class Shipping
{
    const decimal BaseRate = 4.99m;

    // Expression-bodied method, optional parameter with a default value.
    public static decimal Cost(decimal weightKg, bool express = false) =>
        BaseRate + weightKg * 1.20m + (express ? 10m : 0m);

    // Returns a named tuple, like returning { min, max } in TypeScript.
    public static (int Min, int Max) Range(int[] values)
    {
        if (values.Length == 0) throw new ArgumentException("No values", nameof(values));
        int min = values[0], max = values[0];
        foreach (var v in values)
        {
            if (v < min) min = v;
            if (v > max) max = v;
        }
        return (min, max);
    }
}
▶ Try
// The TypeScript version: a module of exported functions.
const BASE_RATE = 4.99;
export function cost(weightKg: number, express = false): number {
  return BASE_RATE + weightKg * 1.2 + (express ? 10 : 0);
}
console.log(cost(2.5).toFixed(2));
  • Every parameter and return type is written out. Inference is for locals (var) and lambdas.
  • static means "belongs to the type, not to an instance". A static class can't be instantiated and holds only static members: it's the C# shape of a utility module.
  • Named arguments (express: true) make call sites readable. Optional parameters need a compile-time constant default.
  • Methods can be overloaded: Cost(decimal) and Cost(decimal, string zone) can both exist.
  • Naming: PascalCase for types, methods, properties and constants; camelCase for locals and parameters; _camelCase for private fields.
  • Throw the specific exception: ArgumentException, ArgumentNullException, ArgumentOutOfRangeException for bad arguments, InvalidOperationException when the object is in the wrong state. nameof(values) gives "values" and survives renames.
  • .NET 8 has guard helpers: ArgumentNullException.ThrowIfNull(x), ArgumentException.ThrowIfNullOrWhiteSpace(s), ArgumentOutOfRangeException.ThrowIfNegative(n).

Control flow

▶ Try
int[] scores = [72, 95, 40, 88];

foreach (var score in scores)          // for...of
{
    if (score >= 90) Console.WriteLine($"{score}: excellent");
    else if (score >= 50) Console.WriteLine($"{score}: pass");
    else Console.WriteLine($"{score}: fail");
}

for (int i = scores.Length - 1; i >= 0; i--)   // classic for, same as TS
{
    if (scores[i] < 50) continue;
    Console.WriteLine($"last passing score: {scores[i]}");
    break;
}

int attempts = 0;
while (attempts < 3) attempts++;
Console.WriteLine($"attempts: {attempts}");

string level = "warn";
switch (level)                          // a switch statement: no fall-through between cases
{
    case "error":
    case "fatal":
        Console.WriteLine("page someone");
        break;
    case "warn":
        Console.WriteLine("log it");
        break;
    default:
        Console.WriteLine("ignore");
        break;
}
  • No truthiness. if (count) and if (name) don't compile. Write count > 0, name is not null, !string.IsNullOrEmpty(name). A whole class of JavaScript bugs disappears.
  • There is no ===. == is the equality operator, and what it compares depends on the type: values for numbers, strings and records, references for most other classes.
  • A switch statement can't fall from one non-empty case into the next. Each section ends with break, return or throw.

Arrays

▶ Try
int[] empty = new int[3];          // fixed length, filled with default values: 0, 0, 0
int[] primes = [2, 3, 5, 7, 11];   // collection expression (C# 12)
string[] names = { "Ada", "Grace" }; // the older initializer syntax

Console.WriteLine(primes.Length);  // 5 (Length, not length; Count on lists)
Console.WriteLine(primes[^1]);     // 11: index from the end, like at(-1)
int[] middle = primes[1..4];       // 3, 5, 7: a range makes a NEW array, like slice(1, 4)
Console.WriteLine(string.Join(",", middle));
Console.WriteLine(string.Join(",", empty));

int[] reversed = (int[])primes.Clone();
Array.Reverse(reversed);           // in place, like TS reverse()
Console.WriteLine(string.Join(",", reversed));
Console.WriteLine(Array.IndexOf(primes, 7));   // 3
// primes[5] = 13;                 // IndexOutOfRangeException at runtime: arrays never grow
  • An array's length is fixed when it's created. Use List<T> (the Collections & LINQ topic) when you need to add and remove.
  • Arrays are reference types. A method that receives an array can change the caller's array, and Array.Sort(xs) sorts in place. Copy first (xs.ToArray(), (int[])xs.Clone() or xs[..]) if the caller didn't ask you to change their data.
  • Out-of-range indexes throw IndexOutOfRangeException. There is no undefined.

const and readonly

TypeScript's const means "this binding can't be reassigned". C# splits the idea:

▶ Try
Console.WriteLine(Limits.MaxItems);
Console.WriteLine(Limits.StartedAt.Year > 2000);
var counter = new Counter(10);
Console.WriteLine(counter.Limit);

public static class Limits
{
    public const int MaxItems = 50;                         // compile-time constant
    public static readonly DateTime StartedAt = DateTime.UtcNow; // set once, at runtime
}

public class Counter
{
    readonly int _limit;                                    // can only be set in a constructor
    public Counter(int limit) => _limit = limit;
    public int Limit => _limit;
}
  • const is for values known at compile time: numbers, bool, char, string. The compiler copies the value into every place that uses it. If another project uses your public const and you change it, that project keeps the old value until it is recompiled. Prefer static readonly for public values that might change.
  • readonly fields can be assigned only in their declaration or a constructor. Like TypeScript's readonly, it protects the field, not the object it points to: a readonly List<int> can still be added to.
  • There is no readonly local variable. Locals are assigned as often as you like, so keep methods short and assign once by habit. (const locals exist for compile-time values.)

Enums

Where TypeScript uses a union of string literals ('pending' | 'paid' | 'shipped'), C# uses an enum: named integer constants with their own type.

▶ Try
var status = OrderStatus.Paid;
Console.WriteLine(status);                              // Paid
Console.WriteLine((int)status);                         // 1
Console.WriteLine(Enum.Parse<OrderStatus>("Shipped"));  // Shipped
Console.WriteLine(status == OrderStatus.Paid);          // True

var weird = (OrderStatus)42;                            // compiles and runs!
Console.WriteLine(weird);                               // 42
Console.WriteLine(Enum.IsDefined(weird));               // False

public enum OrderStatus { Pending, Paid, Shipped, Cancelled }
  • Members are numbered from 0 unless you assign values (Paid = 10). ToString() gives the name, which is how enums end up as strings in logs and (with the right serializer option) in JSON.
  • Any integer can be cast to an enum, even one with no name. Validate enums that come from outside (Enum.IsDefined), and give every switch over an enum a _ arm.

Switch expressions

A switch expression is a switch that produces a value, closer to a TypeScript lookup or a chain of ternaries. It's one of the nicest parts of modern C#:

▶ Try
Console.WriteLine(Describe(0));
Console.WriteLine(Describe(7));
Console.WriteLine(Describe(-3));
Console.WriteLine(Fee("express", 12m));
Console.WriteLine(Fee("standard", 60m));

static string Describe(int n) => n switch
{
    0 => "zero",
    < 0 => "negative",
    > 0 and < 10 => "small",
    _ => "large",                    // _ is the discard: "anything else"
};

static decimal Fee(string speed, decimal orderTotal) => (speed, orderTotal) switch
{
    ("standard", >= 50m) => 0m,      // tuple pattern: match both values at once
    ("standard", _) => 4.99m,
    ("express", _) => 9.99m,
    _ => throw new ArgumentException($"Unknown speed '{speed}'", nameof(speed)),
};
  • Arms are tried top to bottom, and the first match wins. Put specific cases before general ones.
  • Patterns: constants (0, "standard"), relational (< 0, >= 50m), combinators (and, or, not), the discard _, tuple patterns, and when guards (var n when n % 2 == 0).
  • The compiler warns (CS8509) when the arms don't cover every input. If an unmatched value arrives at runtime, it throws SwitchExpressionException. End with _ => throw new ... to make the failure explicit.
  • throw is an expression in C#, so it can sit in an arm, after ?? or in a ternary.

Common mistakes

  • Integer division. 5 / 2 is 2. percent / 100 is 0. Make one operand decimal or double.
  • double for money. Use decimal and the m suffix, and say how to round.
  • Default rounding. Math.Round(2.5) is 2. Pass MidpointRounding.AwayFromZero for "half up".
  • Silent overflow. int wraps at about 2.1 billion. Use long, or checked where overflow is a bug.
  • Mutating the caller's array. Array.Sort and Array.Reverse work in place.
  • Expecting truthiness. if (list) doesn't compile, and if (list.Count > 0) is what you mean.
  • Culture surprises. ToString(), Parse and $"{x:N2}" use the current culture. Pass CultureInfo.InvariantCulture for data, and keep culture-specific formatting for what users see.
  • Swallowing errors with Parse. Wrapping int.Parse in try/catch for expected bad input is slow and noisy. Use TryParse.

In a real codebase

Side note

The Program.cs of an ASP.NET Core minimal API shows most of this lesson at once:

// Program.cs in an ASP.NET Core project (not runnable here)
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/prices/{net:decimal}", (decimal net, int vat = 20) =>
{
    if (vat is < 0 or > 100) return Results.BadRequest("vat must be 0-100");
    var gross = Math.Round(net * (1 + vat / 100m), 2, MidpointRounding.AwayFromZero);
    return Results.Ok(new { net, gross });
});

app.Run();

Top-level statements, var, a lambda with typed parameters, a pattern (is < 0 or > 100), decimal arithmetic with 100m, explicit rounding, and an anonymous object (new { net, gross }) that becomes JSON. ASP.NET Core binds net from the route and vat from the query string, converting the strings to decimal and int for you.

The exercises

  1. Prices with decimal: money arithmetic, integer division and rounding half away from zero.
  2. Format a duration: integer division, %, string interpolation and format strings.
  3. Classify HTTP status codes: switch expressions with relational, or and tuple patterns.
  4. Latency statistics: arrays, copying before sorting, overflow-safe averages and percentiles.
  5. Validate an IBAN: characters, loops and doing arithmetic on a number too big for any integer type.
  6. Split money fairly: allocate cents so the parts always add up, with negative amounts and weights.

Practise this lesson

In the app: a short video, 6 exercises checked by real tests and a 10-question concept check. Free with a GitHub account. Running the exercises against their tests needs Pro.

Open in the app