Types
8 min readTypes
TL;DR
Choosing the right kind of type affects memory layout, equality semantics, mutability, and API contracts. Use these rules of thumb when designing models and DTOs:
How it works
Type Choices β class, record, struct, static (where & why)
class(reference type):- Use for objects with identity, lifecycle, or potentially large mutable state (e.g., domain entities, services).
- Instances are allocated on the heap; assignments copy references, not state.
- Good when you want shared mutable state or polymorphism (virtual methods, inheritance).
- Example:
public class Order { public int Id; public decimal Amount; }
struct(value type):- Use for small, immutable, copy-by-value types that represent a single value (e.g.,
Price,Coordinate). - Avoid large structs (copying cost) or mutable structs (surprising semantics when boxed or assigned).
- Prefer
readonly structfor immutable value semantics. - Example:
public readonly struct Price { public decimal Amount { get; } }
record(reference-record, C# 9+):- Use when you want concise immutable data carriers with value-based equality and non-destructive mutation (
withexpressions). - Ideal for DTOs, messages, and snapshots where equality by content is helpful.
- Records are reference types by default (there is also
record structfor value semantics). - Example:
public record OrderDto(int Id, string Symbol, decimal Amount);
record struct(C# 10+):- Combines record conveniences (auto equality,
with) with value-type semantics β useful for small immutable value objects where structural equality is desired.
staticclasses / members:- Use
staticclasses for stateless helpers, extension method containers, and singletons without state. staticmembers belong to the type rather than instances; no instantiation possible.- Be cautious:
staticmutable state is effectively global and introduces thread-safety concerns. - Example:
public static class Email { public static void Send(...) { ... } }
Practical guidance & trade-offs
- Prefer
recordfor DTOs and immutable data transfer where content equality is useful. - Prefer
classfor domain entities that have an identity (database ID) and lifecycle; they usually need to be mutable or proxied by ORMs. - Use
struct/record structfor very small value objects (e.g.,PriceTick,Timestamp) to avoid heap allocation when copying is cheap. - Favour immutability for simple data carriers β it reduces shared-state bugs and simplifies reasoning, especially across threads.
- Avoid mutable singletons or
staticmutable fields; prefer injected, testable services with clear lifetimes.
Quick examples
// record for DTO
public record OrderDto(int Id, string Symbol, decimal Amount);
// class for entity
public class Order
{
public int Id { get; set; }
public decimal Amount { get; set; }
}
// small readonly struct for value
public readonly struct PriceTick
{
public decimal Bid { get; }
public decimal Ask { get; }
public PriceTick(decimal bid, decimal ask) => (Bid, Ask) = (bid, ask);
}
// static helper
public static class MathHelpers { public static decimal RoundPrice(decimal p) => Math.Round(p, 5); }
Static classes
The compiler emits a static class as abstract sealed, so nothing can create it or derive from it.
- It holds static members only and has no instance constructor.
- It inherits only from
objectand cannot implement an interface. - It cannot be the type of a variable, parameter or generic argument.
- Classic extension methods must be declared in a non-generic, non-nested static class.
public static class StringExtensions
{
private static readonly char[] Separators = [' ', '-'];
public static string[] Words(this string text) =>
text.Split(Separators, StringSplitOptions.RemoveEmptyEntries);
}
public static class Counter<T>
{
public static int Count; // Counter<int>.Count and Counter<string>.Count are separate fields
}
Runtime behaviour to know:
- A static constructor takes no parameters or access modifier. The runtime runs it once, thread-safely, before first use.
- If it throws, that first access gets a
TypeInitializationException, and so does every later access until the process ends. - Each closed generic type has its own static fields.
- Static fields are GC roots: an entry in a static dictionary lives until it is removed.
Use one for pure functions with no dependencies, such as Math.Round. If the code holds state or a test must replace it, inject an instance. DateTime.UtcNow is the classic hidden dependency, which TimeProvider exists to replace.
Partial classes
partial splits one type across several files. The compiler merges the parts, so at runtime there is one ordinary type and no trace of the split.
- Every part has the
partialkeyword, the same name and namespace, and lives in the same assembly. - It works on
class,struct,interfaceandrecord. - Members, attributes and implemented interfaces are combined.
abstractorsealedon one part applies to the whole type. Accessibility and base class must not conflict.- To add to a nested type from another file, every containing type must be
partialtoo.
Partial members split a declaration from its implementation:
| Kind | Declaration | Implementation |
|---|---|---|
| Optional method | partial void X();, no access modifier, no out | Optional. If absent, the compiler removes the declaration and every call to it |
| Required method (C# 9) | Has an access modifier, a return value or out | Mandatory, usually from a source generator |
| Property, indexer (C# 13) | public partial string Name { get; set; } | Mandatory |
| Event, constructor (C# 14) | public partial event EventHandler Changed; | Mandatory |
public static partial class Log
{
[LoggerMessage(Level = LogLevel.Information, Message = "Order {OrderId} placed")]
public static partial void OrderPlaced(ILogger logger, int orderId);
}
public partial class OrderValidator
{
[GeneratedRegex(@"^ORD-\d{6}$")]
private static partial Regex OrderIdPattern();
public bool IsValid(string id) => OrderIdPattern().IsMatch(id);
}
Use it to keep generated code and hand-written code in one type: source generators, WinForms designers, scaffolded EF Core entities. Splitting a 3,000-line class into partial files changes nothing, because it is still one class with every responsibility it had.
If you'd like, I can link this file from core-concepts.md and/or expand it with interview bullet points for quick review.
Quick recall Q&A
record vs class?Use records when you want concise immutable data carriers with value-based equality (DTOs, events). Use classes when identity/lifecycle matters or when you need mutable state and inheritance.
record struct?It combines value semantics (no heap allocation) with generated equality/with expressions. Ideal for small immutable value objects where structural equality is desired.
Copying them is expensive and negates GC benefits. Keep structs small (β€16 bytes) or pass by in/ref to avoid copies.
static classes?For stateless helpers or extension method containers. Avoid static mutable state because itβs effectively global and complicates testing/threading.
static class?An abstract sealed class. It cannot be instantiated or inherited, and it cannot implement interfaces.
The first access gets a TypeInitializationException, and every later access to that type gets one too until the process ends. Load config that can fail explicitly at startup instead.
Counter<int> and Counter<string> share static fields?No. Each closed generic type has its own copy of the static fields.
Static fields are GC roots, so every object the collection references stays alive until it is removed. An unbounded static cache grows for the life of the process.
A singleton is an instance: it can implement an interface, be injected and be replaced in a test. A static class can do none of these, so it suits pure functions only.
partial class?One type written across several files. The compiler merges the parts, all in the same assembly and namespace, so nothing about the split exists at runtime.
partial?A generator can only add files, never edit yours. partial lets its output join your type, as with [GeneratedRegex], [LoggerMessage] and JsonSerializerContext.
For partial void X(); with no access modifier, the compiler removes the declaration and all calls to it, including evaluation of their arguments.
When it has an access modifier, a non-void return or an out parameter (C# 9). A missing implementation is then a compile error.
No. All parts compile together into one assembly, so a partial class cannot extend a type from a package.
partial fix a class that is too big?No. It is still one class with the same responsibilities and shared private state. Extract real types instead.
record equality semantics work?Records implement value-based equality by comparing declared properties/fields. Classes use reference equality unless you override Equals/GetHashCode.
Yes, but it defeats their primary benefit. Prefer init-only setters or positional parameters to keep them immutable and safe across threads.
record inheritance make sense?When modeling hierarchies of immutable data (e.g., different message types). Remember records default to value equality, so ensure derived records add properties carefully.
If you need identity semantics, lazy-loaded navigation properties (e.g., EF proxies), or mutable behavior beyond data transfer.
struct and record struct?If you need value semantics plus generated equality/with, use record struct. If you want full control over equality/toString, a regular struct might suffice.
Many serializers support classes/records out of the box. Structs serialize fine but be mindful of default values and boxing when using polymorphic serialization.