C# types, records and unions
This page covers the C# features you reach for when you decide how a piece of data is shaped and how it moves through code: letting the compiler infer a type, grouping a few values without declaring a class, unpacking those values again, ignoring the parts you do not need, modeling immutable data with value equality, and declaring a fixed set of alternatives that the compiler can check exhaustively. It ends with dynamic, the escape hatch that turns static typing off.
Every sample uses one invented domain, an order-management app called OrdersPortal. Unless a section says otherwise, each sample is a complete file-based app: save it as sample.cs and run dotnet run sample.cs with the .NET 10 SDK (C# 14). The outputs shown were produced with .NET SDK 10.0.115. Samples for C# 15 features need the .NET 11 SDK and are marked “not compiled here”.
Features on this page
Section titled “Features on this page”| Feature | Version | Use it when |
|---|---|---|
| var implicit typing | C# 3 | The type is obvious from the right-hand side, or cannot be named (anonymous types). |
| Default literal | C# 7.1 | You need a type’s default value and the target type is already known. |
| Tuples | C# 7.0 | A method returns two or three related values that do not deserve a named type. |
| Deconstruction | C# 7.0 | You want the parts of a tuple, record or type in separate variables. |
| Discards | C# 7.0 | A value must be accepted syntactically but is intentionally unused. |
| Records | C# 9 (record struct C# 10) | Data is defined by its values: DTOs, messages, value objects. |
| Closed hierarchies | C# 15 | You own a family of classes and want exhaustive switch without a default arm. |
| Union types | C# 15 | A value is exactly one of several existing, unrelated types. |
| Dynamic | C# 4 | COM or dynamic-language interop where static types do not exist. |
var implicit typing
Section titled “var implicit typing”Introduced in C# 3 (.NET Framework 3.5). var asks the compiler to infer a local variable’s type from its initializer. The variable is still statically typed: var total = lines.Sum() is a decimal forever, and assigning a string to it later is a compile error. var exists mainly because LINQ projections produce anonymous types that have no name you could write, but it also removes noise when the type is already spelled out on the right (var map = new Dictionary<string, List<int>>()). var works for locals, for and foreach variables, using declarations and deconstruction; it cannot be used for fields, parameters or return types, and it needs an initializer.
var ordersByCustomer = new Dictionary<string, List<decimal>>{ ["ORD-1001"] = [19.99m, 5.01m], ["ORD-1002"] = [120m],};
foreach (var (orderId, lineTotals) in ordersByCustomer){ var total = lineTotals.Sum(); // decimal, inferred from Sum() var summary = new { orderId, total }; // anonymous type: only var can name it Console.WriteLine($"{summary.orderId}: {summary.total} ({total.GetType().Name})");}Output:
ORD-1001: 25.00 (Decimal)ORD-1002: 120 (Decimal)Pitfalls:
varhides the type from a reader of the line. If the right-hand side is a method call whose return type is not obvious (var result = Process(order)), spell the type out.- Numeric literals infer the narrowest default:
var price = 9.99is adouble, not adecimal. Use themsuffix for money. var x = null;andvar x = default;do not compile because there is nothing to infer from.
Default literal
Section titled “Default literal”Introduced in C# 7.1 (.NET Core 2.0 era, Visual Studio 2017 15.3). Before 7.1 you wrote default(CancellationToken); now plain default works wherever the compiler already knows the target type: assignments, returns, optional parameter values, arguments and comparisons. The value is the type’s zero value: 0 for numbers, false for bool, null for reference types and nullable value types, and an all-zero struct (for example 0001-01-01 for DateOnly). In generic code default is the only way to produce “nothing” for a type parameter that might be either a class or a struct.
static T FirstOrFallback<T>(IReadOnlyList<T> items) => items.Count > 0 ? items[0] : default!;
static decimal ApplyDiscount(decimal subtotal, decimal rate = default, CancellationToken token = default){ token.ThrowIfCancellationRequested(); return subtotal - subtotal * rate;}
int[] noQuantities = [];string[] noCustomers = [];DateOnly[] noDates = [];
Console.WriteLine(FirstOrFallback(noQuantities)); // default(int)Console.WriteLine(FirstOrFallback(noCustomers) ?? "(null)"); // default(string)Console.WriteLine(FirstOrFallback(noDates).ToString("yyyy-MM-dd")); // default(DateOnly)Console.WriteLine(ApplyDiscount(200m)); // rate = 0, token = NoneConsole.WriteLine(ApplyDiscount(200m, 0.15m));Output:
0(null)0001-01-01200170.00Pitfalls:
var x = default;is error CS8716: there is no target type. Writedefault(int)or give the variable a type.- A default struct bypasses its constructor. A
defaultDateOnlyorGuidis a real value that can slip into a database unnoticed. defaultfor a reference type isnull; in a nullable-enabled project the!indefault!silences a warning and should be a deliberate choice.
Tuples
Section titled “Tuples”Introduced in C# 7.0 (.NET Framework 4.7 / .NET Core 2.0, which ship System.ValueTuple). Tuple types such as (int Count, decimal Total) group a few values into a lightweight value type with optional element names. They are ideal for a private or internal method that returns two or three things, and for local grouping inside an algorithm. Element names are a compile-time convenience: the runtime type is ValueTuple<int, decimal> and the fields are really Item1 and Item2. Since C# 7.3, == and != compare tuples element by element and ignore names.
static (int Count, decimal Total) Summarize(IEnumerable<decimal> orderTotals){ int count = 0; decimal total = 0; foreach (var amount in orderTotals) { count++; total += amount; } return (count, total);}
var result = Summarize([10m, 20.5m, 4.5m]);Console.WriteLine($"{result.Count} orders, total {result.Total}");Console.WriteLine(result); // ValueTuple.ToString()
var expected = (Orders: 3, Sum: 35.0m); // different element namesConsole.WriteLine(result == expected); // names are ignored by ==
var copy = result;copy.Total += 1; // tuples are mutable value typesConsole.WriteLine($"{result.Total} vs {copy.Total}");Output:
3 orders, total 35.0(3, 35.0)True35.0 vs 36.0Pitfalls:
- Element names are erased at run time. Serializers and reflection see
Item1,Item2, so tuples make poor public API or JSON contracts; use a record instead. - Tuples are mutable structs that copy on assignment. Changing
copy.Totaldoes not changeresult. - Once a tuple has more than three elements or travels across layers, a named record is easier to read and evolve.
Deconstruction
Section titled “Deconstruction”Introduced in C# 7.0; mixing new declarations and existing variables in one deconstruction arrived in C# 10. Deconstruction splits a value into separate variables in one statement: var (id, total) = order;. It works on tuples, on positional records (the compiler generates a Deconstruct method), on KeyValuePair in .NET Core 2.0 and later, and on any type that has an instance or extension method named Deconstruct with out parameters. The same mechanism powers positional patterns such as Order(var id, _, _, > 100m). Assigning into existing variables gives a temporary-free swap: (a, b) = (b, a).
var order = new Order("ORD-2001", "Fabrikam Outdoor", 3, 74.85m);
var (id, customer, _, total) = order; // calls Order.DeconstructConsole.WriteLine($"{id} for {customer}: {total}");
var line = new OrderLine("SKU-7", 2);var (sku, quantity) = line; // positional recordConsole.WriteLine($"{sku} x{quantity}");
string primary = "warehouse-east", fallback = "warehouse-west";(primary, fallback) = (fallback, primary); // swap without a tempConsole.WriteLine($"{primary}, {fallback}");
string status;(status, var retries) = ("Pending", 2); // C# 10: mix assignment and declarationConsole.WriteLine($"{status} after {retries} retries");
public sealed class Order(string id, string customer, int lineCount, decimal total){ public string Id { get; } = id; public string Customer { get; } = customer; public int LineCount { get; } = lineCount; public decimal Total { get; } = total;
public void Deconstruct(out string id, out string customer, out int lineCount, out decimal total) => (id, customer, lineCount, total) = (Id, Customer, LineCount, Total);}
public record OrderLine(string Sku, int Quantity);Output:
ORD-2001 for Fabrikam Outdoor: 74.85SKU-7 x2warehouse-west, warehouse-eastPending after 2 retriesPitfalls:
- Deconstruction is positional. Reordering the parameters of a record or
Deconstructmethod silently swaps values at every call site that has the same types. - An extension
Deconstructis only found when its namespace is imported. - A
dynamicvalue cannot be deconstructed (error CS8133); convert it to a static type first.
Discards
Section titled “Discards”Introduced in C# 7.0; lambda parameter discards such as (_, _) => ... arrived in C# 9. A discard, written _, is a write-only placeholder for a value you are required to accept but do not use. It appears in out arguments (out _), deconstruction (var (_, _, total) = ...), patterns (the _ arm of a switch expression), lambda parameters, and as a standalone assignment (_ = Task) that tells readers and analyzers the result is ignored on purpose. Each _ is a separate target with no storage, so you can use several in one statement and their types may differ.
string[] rawQuantities = ["3", "x", "12"];foreach (var raw in rawQuantities){ // Only the success flag matters here, so the parsed value is discarded. Console.WriteLine($"{raw}: {(int.TryParse(raw, out _) ? "valid" : "invalid")}");}
var (_, _, total) = GetOrder(); // keep only the totalConsole.WriteLine($"Total: {total}");
Func<string, int, string> ignoreArgs = (_, _) => "n/a"; // C# 9 lambda discardsConsole.WriteLine(ignoreArgs("ORD-1", 1));
_ = ValidateAsync("ORD-3001"); // deliberately not awaited: errors are lostawait Task.Delay(50);
static string Classify(decimal total) => total switch{ >= 1000m => "large", >= 100m => "medium", _ => "small",};Console.WriteLine(Classify(total));
static (string Id, string Customer, decimal Total) GetOrder() => ("ORD-3001", "Tailspin Toys", 249.90m);
static async Task ValidateAsync(string id){ await Task.Yield(); Console.WriteLine($"Validated {id}");}Output:
3: validx: invalid12: validTotal: 249.90n/aValidated ORD-3001mediumPitfalls:
_ = SomeAsync()drops the task, and any exception it throws is never observed. Use it only for genuine fire-and-forget work that handles its own errors.- If a variable named
_is already in scope (for example a single-parameter lambda_ => ...),_is that variable, not a discard. - A
_arm in a switch accepts every future case, so it hides missing cases that the compiler would otherwise report. See Closed hierarchies.
Records
Section titled “Records”Introduced in C# 9 (.NET 5); record struct and the explicit record class spelling arrived in C# 10 (.NET 6). A record is a class or struct whose identity is its data. The compiler generates value-based Equals, GetHashCode, == and !=, a readable ToString, and support for with expressions that copy the record with some properties changed. A positional record, record OrderLine(string Sku, int Quantity, decimal UnitPrice), also gets a primary constructor, init-only properties and a Deconstruct method. Use records for DTOs, messages, events and value objects; keep classes for entities whose identity survives changes to their data.
var line = new OrderLine("SKU-100", 2, 9.99m);var updated = line with { Quantity = 3 }; // nondestructive copy
Console.WriteLine(line);Console.WriteLine(updated);Console.WriteLine(line == updated with { Quantity = 2 }); // value equality
var price = new Money(19.98m, "EUR");var (amount, currency) = price;Console.WriteLine($"{amount} {currency}");
var a = new TaggedOrder("ORD-1", ["gift"]);var b = new TaggedOrder("ORD-1", ["gift"]);Console.WriteLine(a == b); // false: the lists are different instances
public record OrderLine(string Sku, int Quantity, decimal UnitPrice){ public decimal Total => Quantity * UnitPrice;}
public readonly record struct Money(decimal Amount, string Currency);
public record TaggedOrder(string Id, List<string> Tags);Output:
OrderLine { Sku = SKU-100, Quantity = 2, UnitPrice = 9.99, Total = 19.98 }OrderLine { Sku = SKU-100, Quantity = 3, UnitPrice = 9.99, Total = 29.97 }True19.98 EURFalsePitfalls:
- Equality is shallow. A collection property compares by reference, so two records with equal list contents are not equal, as the last line shows.
withmakes a shallow copy: both records share the same list instance.- Records are immutable only by convention. Positional records use
init, but you can still addsetproperties or mutable collections.
Closed hierarchies
Section titled “Closed hierarchies”Introduced in C# 15 (.NET 11, November 2026); not a preview feature. The closed modifier on a class says “all direct subclasses live in this assembly”. Because the compiler can see every direct descendant, a switch that handles each one is exhaustive and needs no _ arm, and adding a new descendant produces a warning at every switch that does not handle it yet. A closed class is implicitly abstract and cannot also be sealed, static or explicitly abstract. Use it for a family of types you own that share state or behavior: payment states, workflow steps, API results.
Not compiled here (needs .NET 11 SDK); syntax verified against the Microsoft Learn C# 15 documentation.
Console.WriteLine(Describe(new Authorized(74.85m)));Console.WriteLine(Describe(new Declined("card expired")));
static string Describe(PaymentState state) => state switch{ Pending => "waiting for the card issuer", Authorized(var amount) => $"authorized {amount:0.00}", Declined d => $"declined: {d.Reason}", // No _ arm: every direct descendant of PaymentState is handled.};
public closed record class PaymentState;public record class Pending : PaymentState;public record class Authorized(decimal Amount) : PaymentState;public record class Declined(string Reason) : PaymentState;Expected output:
authorized 74.85declined: card expiredPitfalls:
- Closure is not transitive. A non-closed descendant can be extended in other assemblies; mark intermediate classes
closedas well if you switch on them. - Adding a
_arm “to be safe” throws away the benefit: the compiler can no longer tell you about a new case. - Code outside the declaring assembly cannot derive directly from the closed class, which can break test doubles that subclassed it.
Union types
Section titled “Union types”Introduced in C# 15 (.NET 11, November 2026); not a preview feature. A union declaration, union OrderStatus(Shipped, Backordered, Cancelled), says that a value is exactly one of a list of existing case types. Each case type converts implicitly to the union, type patterns test the union’s contents, and a switch that covers every case type is exhaustive. Unlike a closed hierarchy, the case types do not share a base class, so a union can combine types you do not own, such as string and int. The compiler lowers the declaration to a struct marked with UnionAttribute that implements IUnion and stores the contents in an object? Value property; those types ship in the .NET 11 runtime.
Not compiled here (needs .NET 11 SDK); syntax verified against the Microsoft Learn union types reference.
OrderStatus status = new Shipped("TRK-48213"); // implicit union conversionConsole.WriteLine(Describe(status));Console.WriteLine(Describe(default));
static string Describe(OrderStatus status) => status switch{ Shipped s => $"shipped, tracking {s.TrackingNumber}", Backordered b => $"back in stock {b.ExpectedDate:yyyy-MM-dd}", Cancelled c => $"cancelled: {c.Reason}", null => "no status yet", // default(OrderStatus) has null contents};
public record class Shipped(string TrackingNumber);public record class Backordered(DateOnly ExpectedDate);public record class Cancelled(string Reason);
public union OrderStatus(Shipped, Backordered, Cancelled);Expected output:
shipped, tracking TRK-48213no status yetPitfalls:
- A default union (an uninitialized field or array element) has null contents. If the
nullarm is missing, the switch throwsSwitchExpressionExceptionat run time even though the compiler may not warn. - Value-type cases such as
intare boxed in the generated union. Write a custom union type withHasValueandTryGetValuemembers if boxing matters. pet is Petdoes not test the union instance; type patterns look at the contents (error CS8121 if no case type can match).
Dynamic
Section titled “Dynamic”Introduced in C# 4 (.NET Framework 4). A variable typed dynamic skips compile-time member checking: every member access, call and operator on it is bound at run time by the C# runtime binder. That makes Office COM automation, IronPython-style interop and ExpandoObject scripting readable, at the price of losing IntelliSense, refactoring safety and performance. A missing member becomes a RuntimeBinderException instead of a compile error. Dynamic binding also relies on runtime code generation, so it is incompatible with Native AOT; file-based apps publish with AOT by default, which is why this sample sets PublishAot=false.
#:property PublishAot=falseusing System.Dynamic;using System.Text.Json;using Microsoft.CSharp.RuntimeBinder;
dynamic row = new ExpandoObject();row.OrderId = "ORD-4001";row.Total = 42.50m;Console.WriteLine($"{row.OrderId}: {row.Total}");
try{ Console.WriteLine(row.Customer); // compiles; fails at run time}catch (RuntimeBinderException ex){ Console.WriteLine($"Binder error: {ex.Message}");}
// JsonSerializer does not create dynamic objects: dynamic here is a JsonElement.dynamic json = JsonSerializer.Deserialize<dynamic>("""{"orderId":"ORD-4002"}""")!;Console.WriteLine(json.GetType().Name);try{ Console.WriteLine(json.orderId);}catch (RuntimeBinderException){ Console.WriteLine("JsonElement has no orderId member");}Output:
ORD-4001: 42.50Binder error: 'System.Dynamic.ExpandoObject' does not contain a definition for 'Customer'JsonElementJsonElement has no orderId memberPitfalls:
JsonSerializer.Deserialize<dynamic>returns aJsonElement, not an object with JSON properties. UseJsonNodeor a typed model instead.- Dynamic code produces trimming and AOT warnings (IL2026, IL3050) and fails under Native AOT.
dynamicspreads: any expression that involves a dynamic value is itself dynamic, so cast back to a static type as early as possible.
Choosing between them
Section titled “Choosing between them”- A few values from one private method: a tuple. Data that crosses a layer or is serialized: a record.
- A value object such as Money: a
readonly record struct. An entity with an identity that outlives its data: a class. - A fixed family of types you own and that share members: a closed hierarchy. A choice between existing, unrelated types: a union.
- Ignoring a value: a discard, not a dummy variable. Not knowing the type at all: first look for
JsonNode, generics or an interface; usedynamiconly for real dynamic interop.
Interview questions
Section titled “Interview questions”Is var dynamic typing?
No. var is resolved at compile time and the variable has one fixed static type. dynamic is a static type that tells the compiler to defer member binding to run time; mistakes surface as RuntimeBinderException.
Why are two records with the same list contents not equal?
Generated equality compares each field with EqualityComparer<T>.Default. For List<T> that is reference equality, so equality is shallow. Use immutable collections with structural comparison, override Equals for that member, or keep collections out of value objects.
When would you return a tuple instead of a record? For private or internal helpers that return two or three closely related values to a caller that immediately deconstructs them. Tuple names are erased at run time, so for public APIs, serialization and anything that needs documentation or evolution, a record is better.
What is the difference between a closed hierarchy and a union type in C# 15?
A closed hierarchy is a base class whose direct subclasses must live in the same assembly; the cases share members and you own them all. A union lists existing case types that need no common base, even int and string. Both give exhaustive switches.
Senior scenario: an OrderResult base class has subclasses Success, ValidationFailed and PaymentFailed, and every switch over it ends with _ => throw. A new FraudReview case shipped and crashed production. How would you prevent this?
The _ arm turned a compile-time problem into a run-time crash. On C# 15, mark OrderResult as closed (it is your hierarchy and the cases share members), remove the default arms, and treat warning CS8509 (non-exhaustive switch) as an error. Adding FraudReview then breaks the build at every switch that does not handle it. If the project must stay on .NET 10, the fallback is a visitor interface or an abstract method per case, plus a test that enumerates subclasses by reflection.
Related pages
Section titled “Related pages”- Pattern matching: the patterns that consume records, tuples, closed hierarchies and unions.
- Object construction and initialization: primary constructors,
initandrequiredmembers used by records. - Null handling: nullable reference types and the
defaultvalues shown above. - Methods, lambdas and extensions:
outvariables andDeconstructextension methods. - C# 15 release guide and C# version history.