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.
In short
- Methods live in types: a
static classis your module varis inference, notanyint / inttruncates;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>
TargetFrameworkis the runtime version, liketarget/libintsconfig.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.Nullableturns on nullable reference types:stringcan't be null,string?can. It is thestrictNullChecksof C#, and every modern codebase has it on.ImplicitUsingsimports common namespaces (System,System.Linq,System.Collections.Generic,System.Threading.Tasks...) into every file, so you don't write them at the top.PackageReferenceis a NuGet package, like a dependency inpackage.json. There is nonode_modulesfolder: packages live in a shared cache.- Unlike
tsconfig'sinclude, you don't list source files. Every.csfile 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.csholdsExample.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.publictypes are visible to other projects.internal(the default for a top-level type) means "only inside this project". Members of a class areprivateby 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
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})");
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# | Size | Literal | Use it for |
|---|---|---|---|
int | 32-bit | 42 | counts, indexes, ids. The default integer. |
long | 64-bit | 42L | big counts, file sizes, Unix milliseconds |
double | 64-bit float | 4.2, 4.2d | measurements, maths, ratios. Same as a JS number. |
float | 32-bit float | 4.2f | graphics and ML APIs that ask for it |
decimal | 128-bit base-10 | 4.2m | money, anything a human adds up on paper |
bool | true | no truthiness: conditions must be bool | |
char | 16-bit | 'x' | a single character |
string | reference | "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:
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:
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:
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:
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
msuffix is required.decimal d = 19.99;doesn't compile, because19.99is adoubleand C# won't silently convert it. Math.Roundrounds halves to the nearest even digit by default ("banker's rounding"). SayMidpointRounding.AwayFromZerowhen the business rule says "round half up".- Mixing
decimalanddoubleneeds an explicit cast. That's the compiler stopping a precision bug. In SQL Server and EF Core,decimal(18,2)columns map todecimal. - A
decimalremembers its trailing zeros:2.5m * 1.20mis3.000m, and it prints that way. The value still equals3m(==ignores the scale). Format withF2orN2when you display it.
Converting and parsing
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 andstructs) hold their data directly. Assigning or passing one copies it. - Reference types (
string, arrays,List<T>, classes, records other thanrecord 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.
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
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,,8sets a width (negative means left-aligned) and:N2is 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.5withN2is1,234.50inen-USand1.234,50inde-DE. For machine-readable output (logs, CSV, JSON, URLs) format withCultureInfo.InvariantCulture. The lab runs with the invariant culture, which formats likeen-US. - Strings are immutable. Building one in a loop with
+=copies it every time. UseStringBuilderorstring.Joinfor 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
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);
}
}
// 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. staticmeans "belongs to the type, not to an instance". Astatic classcan'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)andCost(decimal, string zone)can both exist. - Naming:
PascalCasefor types, methods, properties and constants;camelCasefor locals and parameters;_camelCasefor private fields. - Throw the specific exception:
ArgumentException,ArgumentNullException,ArgumentOutOfRangeExceptionfor bad arguments,InvalidOperationExceptionwhen 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
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)andif (name)don't compile. Writecount > 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
switchstatement can't fall from one non-empty case into the next. Each section ends withbreak,returnorthrow.
Arrays
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()orxs[..]) if the caller didn't ask you to change their data. - Out-of-range indexes throw
IndexOutOfRangeException. There is noundefined.
const and readonly
TypeScript's const means "this binding can't be reassigned". C# splits the idea:
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;
}
constis 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 yourpublic constand you change it, that project keeps the old value until it is recompiled. Preferstatic readonlyfor public values that might change.readonlyfields can be assigned only in their declaration or a constructor. Like TypeScript'sreadonly, it protects the field, not the object it points to: areadonly List<int>can still be added to.- There is no
readonlylocal variable. Locals are assigned as often as you like, so keep methods short and assign once by habit. (constlocals 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.
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 everyswitchover 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#:
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, andwhenguards (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. throwis an expression in C#, so it can sit in an arm, after??or in a ternary.
Common mistakes
- Integer division.
5 / 2is2.percent / 100is0. Make one operanddecimalordouble. doublefor money. Usedecimaland themsuffix, and say how to round.- Default rounding.
Math.Round(2.5)is2. PassMidpointRounding.AwayFromZerofor "half up". - Silent overflow.
intwraps at about 2.1 billion. Uselong, orcheckedwhere overflow is a bug. - Mutating the caller's array.
Array.SortandArray.Reversework in place. - Expecting truthiness.
if (list)doesn't compile, andif (list.Count > 0)is what you mean. - Culture surprises.
ToString(),Parseand$"{x:N2}"use the current culture. PassCultureInfo.InvariantCulturefor data, and keep culture-specific formatting for what users see. - Swallowing errors with
Parse. Wrappingint.Parseintry/catchfor expected bad input is slow and noisy. UseTryParse.
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
- Prices with decimal: money arithmetic, integer division and rounding half away from zero.
- Format a duration: integer division,
%, string interpolation and format strings. - Classify HTTP status codes: switch expressions with relational,
orand tuple patterns. - Latency statistics: arrays, copying before sorting, overflow-safe averages and percentiles.
- Validate an IBAN: characters, loops and doing arithmetic on a number too big for any integer type.
- 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