Types

8 min read
Mid-level7 min read
Rapid overview

Types

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 struct for 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 (with expressions).
  • Ideal for DTOs, messages, and snapshots where equality by content is helpful.
  • Records are reference types by default (there is also record struct for 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.
  • static classes / members:
  • Use static classes for stateless helpers, extension method containers, and singletons without state.
  • static members belong to the type rather than instances; no instantiation possible.
  • Be cautious: static mutable state is effectively global and introduces thread-safety concerns.
  • Example: public static class Email { public static void Send(...) { ... } }

Practical guidance & trade-offs

  • Prefer record for DTOs and immutable data transfer where content equality is useful.
  • Prefer class for domain entities that have an identity (database ID) and lifecycle; they usually need to be mutable or proxied by ORMs.
  • Use struct/record struct for 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 static mutable 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 object and 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 partial keyword, the same name and namespace, and lives in the same assembly.
  • It works on class, struct, interface and record.
  • Members, attributes and implemented interfaces are combined.
  • abstract or sealed on 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 partial too.

Partial members split a declaration from its implementation:

KindDeclarationImplementation
Optional methodpartial void X();, no access modifier, no outOptional. If absent, the compiler removes the declaration and every call to it
Required method (C# 9)Has an access modifier, a return value or outMandatory, 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

Q: When do you use 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.

Q: What’s the benefit of 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.

Q: Why avoid large structs?

Copying them is expensive and negates GC benefits. Keep structs small (≀16 bytes) or pass by in/ref to avoid copies.

Q: When do you choose static classes?

For stateless helpers or extension method containers. Avoid static mutable state because it’s effectively global and complicates testing/threading.

Q: What does the compiler emit for a static class?

An abstract sealed class. It cannot be instantiated or inherited, and it cannot implement interfaces.

Q: What happens if a static constructor throws?

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.

Q: Do Counter<int> and Counter<string> share static fields?

No. Each closed generic type has its own copy of the static fields.

Q: Why can a static collection leak memory?

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.

Q: What is a static class vs a singleton?

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.

Q: What is a 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.

Q: Why do source generators need partial?

A generator can only add files, never edit yours. partial lets its output join your type, as with [GeneratedRegex], [LoggerMessage] and JsonSerializerContext.

Q: What happens to an optional partial method with no implementation?

For partial void X(); with no access modifier, the compiler removes the declaration and all calls to it, including evaluation of their arguments.

Q: When must a partial method have an implementation?

When it has an access modifier, a non-void return or an out parameter (C# 9). A missing implementation is then a compile error.

Q: Can parts of a partial class live in different assemblies?

No. All parts compile together into one assembly, so a partial class cannot extend a type from a package.

Q: Does 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.

Q: How do record equality semantics work?

Records implement value-based equality by comparing declared properties/fields. Classes use reference equality unless you override Equals/GetHashCode.

Q: Can records be mutable?

Yes, but it defeats their primary benefit. Prefer init-only setters or positional parameters to keep them immutable and safe across threads.

Q: When does 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.

Q: When should you convert a record to a class?

If you need identity semantics, lazy-loaded navigation properties (e.g., EF proxies), or mutable behavior beyond data transfer.

Q: How do you select between 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.

Q: How do type choices impact serialization?

Many serializers support classes/records out of the box. Structs serialize fine but be mindful of default values and boxing when using polymorphic serialization.

See also