Catalog My learning Blog
Full-Stack Developer Course: React, .NET and SQL Server · Phase 1 · Lesson 3 · 6 min read

C# for TypeScript Developers: Types and Nullability

On this page
  1. Learning Objective
  2. Concept Explanation
  3. Worked Example: A Payload Type, Equality and Null Safety
  4. Real-World Examples
  5. Review Questions & Answers

Learning Objective

Translate the TypeScript type system you know into C#, distinguish value types from reference types and understand why it matters for equality and copying, use records for immutable data, and apply nullable reference types so the compiler warns about possible null dereferences.

Concept Explanation

TypeScript types are erased at compile time and describe the shape of data that is really just JavaScript objects. C# types are real: they exist at runtime, determine how memory is laid out, and cannot be bypassed with a cast to any. That single fact explains most of the differences. A C# variable of type int holds a 32-bit integer, always; a variable of type string holds text, always; and passing the wrong thing is a compile error, not a runtime surprise. When a JSON payload arrives from the network, C# code deserializes it into a specific type, and anything that does not fit is rejected at that boundary, which is a natural place to enforce input validity.

C# splits types into value types and reference types. Value types, such as int, decimal, bool, DateTime, and any struct, are copied when assigned or passed. Reference types, such as classes, arrays, and strings, are shared by reference: two variables can point at the same object, and changing it through one is visible through the other. JavaScript has a similar split between primitives and objects, so this should feel familiar. The practical consequence is equality: by default, two distinct class instances with identical fields are not equal, because the comparison checks identity, while two structs with identical fields are equal.

Records fix that awkwardness for data. A record is a class, or optionally a struct, with value-based equality, a readable ToString, and non-destructive mutation using a with expression. Records are the natural C# equivalent of a TypeScript readonly type or interface for describing request and response payloads, which is why ASP.NET Core examples use them constantly. The positional syntax, public record Product(int Id, string Name, decimal Price), declares the properties, constructor, equality, and deconstruction in one line. Prefer immutable records for data transfer objects, because objects that cannot change after construction are far easier to reason about in concurrent server code.

Nullability is where C# and strict TypeScript agree most. With nullable reference types enabled, which the project template does by default, a string means never null and a string with a question mark means possibly null. The compiler tracks this through your code and warns when you dereference something that might be null. This is the same idea as strictNullChecks, and it matters for security as well as stability: null reference exceptions are among the most common causes of unhandled 500 errors, and unhandled errors can leak stack traces or crash request handling if they are not contained. For money, always use decimal, never double, because binary floating point cannot represent values like 0.10 exactly.

IdeaTypeScriptC#
Types at runtimeErasedReal, enforced by the runtime
Number typesnumber onlyint, long, decimal, double, and more
Immutable data shapereadonly interface or typerecord with init-only properties
Null safetystrictNullChecksNullable reference types (string vs string?)
Copy with a changeSpread: {...obj, x: 1}with expression: obj with { X = 1 }
Equality of objectsReference only (===)Reference for classes, value for records and structs

Worked Example: A Payload Type, Equality and Null Safety

The snippet defines a record for an incoming payload, shows value equality and non-destructive updates, and demonstrates how nullable annotations turn a potential crash into a compile-time warning. It also shows why decimal matters for money.

C#
public record TaskItem(int Id, string Title, string? Notes, DateTime? DueDate, decimal Estimate);

var a = new TaskItem(1, "Write report", null, null, 2.5m);
var b = new TaskItem(1, "Write report", null, null, 2.5m);

Console.WriteLine(a == b);              // True: records compare by value
Console.WriteLine(ReferenceEquals(a, b)); // False: still two objects

var renamed = a with { Title = "Write final report" }; // a is unchanged

// Nullable reference types: Notes is string?, so the compiler warns here.
// int len = a.Notes.Length;             // warning CS8602: possible null dereference
int len = a.Notes?.Length ?? 0;          // safe: null-conditional plus a default

// Why decimal for money:
Console.WriteLine(0.1 + 0.2 == 0.3);     // False with double
Console.WriteLine(0.1m + 0.2m == 0.3m);  // True with decimal

In TypeScript you would write the same shape as a readonly interface and use the spread operator to copy it. The key difference is that the C# version is enforced at runtime: a JSON body with a string where the Estimate should be a number fails to deserialize instead of quietly flowing through the system.

A class compares by identity, a struct copies and compares by value, and a record gives a reference type value-based equality, immutability and the with expression.
A class compares by identity, a struct copies and compares by value, and a record gives a reference type value-based equality, immutability and the with expression.

Real-World Examples

  • Tony Hoare, who introduced the null reference in ALGOL W in 1965, called it his billion-dollar mistake in a 2009 conference talk, citing the countless errors and vulnerabilities it has caused. Nullable reference types, added to C# in version 8 in 2019, are the language's direct response, moving the check from runtime crash to compile-time warning.
  • Financial software in every language avoids binary floating point for currency for exactly the reason shown above. Microsoft's own guidance for C# recommends decimal for financial calculations, and mainstream payment APIs such as Stripe represent amounts as integers in the smallest currency unit, which avoids fractional rounding entirely.
Key TakeawaysC# types are real at runtime, split into value types that copy and reference types that share, which changes how data moves through your code. Records give you immutable, value-equal data types ideal for API payloads. Keep nullable reference types enabled, treat every warning as a possible production crash, and use decimal for money.

Review Questions & Answers

For a normal class, the default equality compares object identity, meaning whether both variables point at the same instance in memory, so two separately created objects are never equal. A record generates equality that compares the values of all its fields, so two records with the same data are equal. That makes records the right choice for data transfer objects and test assertions, while entities with a database identity are usually compared by their key.

It declares that the value may be null, whereas a plain string is promised never to be null. The compiler performs flow analysis and emits a warning wherever you use a possibly null value without checking it first. Combined with warnings-as-errors this prevents a large class of null reference exceptions from ever reaching production, and it documents in the type itself which fields are optional.

Double stores binary fractions, so many decimal values such as 0.1 cannot be represented exactly, and small errors accumulate across additions and multiplications. Totals can end up off by a fraction of a cent, which breaks reconciliation, invoices, and tests that compare amounts. Decimal stores base-ten digits precisely, so financial arithmetic behaves the way people expect.

The deserializer converts the incoming JSON into a specific C# type and rejects values that do not fit, such as text where a number is required, before your business logic sees them. That does not replace validation of ranges and business rules, but it removes a whole category of type confusion. In a JavaScript server the same payload could flow through as an unexpected type and fail somewhere far from where it entered.