.NET Development

C# Class Types in C# 14: Which One to Choose and When

Team Nippysoft
• • 15 min read
C# Class Types in C# 14: Which One to Choose and When

A list of "class types in C#" making the rounds on LinkedIn names eight: regular, abstract, static, record, partial, generic, sealed and nested. It works as a map. As a decision aid it falls short, because it mixes three different questions. Abstract, static and sealed answer whether the type can be instantiated and inherited. Record decides how objects are compared. Partial, generic and nested don't compete with any of them: they combine with them, and nothing stops you from writing a sealed partial class Cache<T> nested inside another class.

This guide sorts those pieces out for C# 14, the current stable language version, which ships with .NET 10. Each type gets a compiled example, the case where it fits and, where there is one, the compiler error you get when it's misused. It adds what that list leaves out: record struct, file types, why sealing helps the JIT, the difference between abstract and virtual, and the C# 14 features that touch classes. It ends with a decision table and a look at C# 15, still in preview.

Which C# version this guide covers

C# 14 is the latest stable version, and it's supported on .NET 10 and later. .NET 10 is a long-term support (LTS) release maintained until November 2028; the most recent update is 10.0.14, from October 25, 2026. .NET 11 and C# 15 are still at release candidate 3 (RC3), and Microsoft announced it will launch .NET 11 at .NET Conf, November 10-12, 2026. Once it ships, we'll update the C# 15 section.

The language version is set by the target framework (the TFM), not by the installed compiler: a net10.0 project uses C# 14, and #error version confirms it with Language version: 14.0. That's why a C# 14 sample fails in a net9.0 project, which uses C# 13: field gives CS9260, the partial constructor gives CS0246, and the extension block isn't even parsed. The fix is to move the TFM forward: forcing a newer version is unsupported, and the docs say not to set LangVersion to latest.

Eight names, three questions

Separating the axes avoids questions that don't exist, like whether a class should be "partial or sealed": it can be both.

  1. Can it be instantiated? Can it be inherited? Modifiers answer this: none (a regular class), abstract, static or sealed. Some rule each other out: abstract sealed is error CS0418, and static already implies sealed.
  2. How are objects compared? The declaration form decides: class, record (or record class) or record struct, which is a value type and not a class.
  3. How is the code organized? partial, generic type parameters, nesting and file add on top of any of the answers above.

Regular class: the starting point

A class is a reference type you instantiate with new. It inherits from a single base, implements any number of interfaces, and its derived classes inherit every member except constructors and finalizers.

public class Account
{
    public string Holder { get; }
    public decimal Balance { get; private set; }

    public Account(string holder) => Holder = holder;

    public void Deposit(decimal amount)
    {
        ArgumentOutOfRangeException.ThrowIfNegativeOrZero(amount);
        Balance += amount;
    }
}

It's the default choice for objects with state and behavior. What almost nobody decides is whether it allows inheritance: without sealed, anyone can derive from it.

Abstract: abstract requires, virtual allows

An abstract class exists to be a base: calling new on it is error CS0144. It mixes abstract members, which have no implementation, with complete methods and constructors. The list above describes it as base behavior that derived classes can implement or override, and that phrase blends two different keywords:

  • abstract requires: a derived class that doesn't implement the member doesn't compile (CS0534).
  • virtual allows: the derived class may redefine it with override or keep the base version.
  • With neither, the method isn't virtual, which is the default in C#. Overriding it is error CS0506.
public abstract class Notifier
{
    // Not virtual: no derived class can change the order of the steps.
    public string Send(string message) => Deliver(Format(message));

    // virtual: a derived class MAY override it.
    protected virtual string Format(string message) => message.Trim();

    // abstract: a derived class MUST implement it.
    protected abstract string Deliver(string message);
}

public sealed class ConsoleNotifier : Notifier
{
    protected override string Format(string message) => $"[notice] {base.Format(message)}";

    protected override string Deliver(string message)
    {
        Console.WriteLine(message);
        return message;
    }
}

Notifier notifier = new ConsoleNotifier();
notifier.Send("  order ready  "); // → [notice] order ready

The example locks the algorithm into a non-virtual method, Send, and leaves derived classes one required step and one optional step. With email, SMS and console notifications, each channel implements Deliver, and only the one that needs it changes the format.

The common mistake is marking everything virtual "just in case": every virtual member is a spot where a derived class can break what the base assumes. If there's no shared state or code, an interface may be enough.

Sealed: design and performance

sealed prevents inheriting from the class (CS0509). Sealing is first a design decision, but it's also about performance: when the JIT can see that an object's type is sealed, it knows which method will run and can call it directly, with no virtual dispatch. We checked with the JIT disassembly in Release (DOTNET_TieredCompilation=0 and DOTNET_JitDisasm): two identical classes that override a virtual M() from the base to return 2, one sealed and one not, and a method that adds 42 to the result.

; Test:Unsealed(), unsealed class: virtual dispatch (26 bytes)
mov      rcx, gword ptr [rcx+0x08]
mov      rax, qword ptr [rcx]
mov      rax, qword ptr [rax+0x40]
call     [rax+0x20]Base:M():int:this
add      eax, 42

; Test:Sealed(), sealed class: no call (12 bytes)
mov      rax, gword ptr [rcx+0x10]
cmp      byte  ptr [rax], al
mov      eax, 44

The unsealed class goes through a virtual dispatch (call [rax+0x20]). The sealed one has no call: the JIT devirtualized M(), inlined it and folded 2 + 42 into the constant 44. Sealing also makes type checks such as is cheaper, which is why more than 2,300 internal and private classes across dotnet/runtime were sealed in .NET 6.

That doesn't justify promising percentages. The disassembly above comes from code optimized from the start with no PGO (profile-guided optimization); with the default configuration, the JIT might devirtualize some unsealed calls too. The docs say calls to sealed class members can be "slightly faster", and that's as far as the claim goes.

Rule CA1852, in the Performance category since .NET 7, does the remembering for you. It flags types with no subtypes that aren't visible outside the assembly, but it's off by default, in .NET 10 too: our unsealed internal class built with 0 warnings. Turn it on in .editorconfig:

# .editorconfig
[*.cs]
dotnet_diagnostic.CA1852.severity = warning

# dotnet build:
# warning CA1852: Type 'NotSealed' can be sealed because it has no subtypes
# in its containing assembly and is not externally visible

A public library is a different call: if you want others to extend a type, leave it unsealed and mark virtual only the extension points you intend to support.

Static: no instances and, since C# 14, home of extensions

A static class holds only static members, can't be instantiated (CS0712) and is sealed: inheriting from it is CS0709, and an instance member is CS0708. C# 14 gives it a second job: top-level, non-generic static classes can declare extension blocks, with extension properties in addition to methods, plus members that extend the type rather than an instance.

public static class Converter
{
    public static double CelsiusToFahrenheit(double celsius) => celsius * 9 / 5 + 32;
}

// C# 14: extension members, inside a static class.
public static class TextExtensions
{
    extension(string text) // extends every string instance
    {
        public bool IsBlank => string.IsNullOrWhiteSpace(text); // extension property

        public string Truncate(int max) => text.Length <= max ? text : text[..max];
    }

    extension(string) // extends the string type, not an instance
    {
        public static string Separator => " | ";
    }
}

Console.WriteLine(Converter.CelsiusToFahrenheit(25));            // → 77
Console.WriteLine($"{"".IsBlank}{string.Separator}{"Nippysoft".Truncate(5)}"); // → True | Nippy

The cost of static code doesn't change: you can't swap it out in a unit test, and it holds no per-instance state. A function that needs a clock or a configuration belongs in a regular class that gets injected.

record and record struct: value equality

record (or record class) is a reference type to which the compiler adds value equality, the with expression and a readable ToString. record struct is a value type, not a class: exactly what's missing when records show up in a list of class types.

public record Order(int Id, string Customer, decimal Total);

public readonly record struct Coordinate(double Latitude, double Longitude);

var o1 = new Order(1, "Ana", 99.90m);
var o2 = new Order(1, "Ana", 99.90m);
var o3 = o1 with { Total = 120m };
Console.WriteLine($"{o1 == o2} {ReferenceEquals(o1, o2)}"); // → True False
Console.WriteLine(o3); // → Order { Id = 1, Customer = Ana, Total = 120 }

var c1 = new Coordinate(10.5, 20.25);
var c2 = c1; // copies the value, not a reference
Console.WriteLine($"{c1 == c2} {c1}"); // → True Coordinate { Latitude = 10.5, Longitude = 20.25 }

Two orders with the same data are equal even though they're different objects, and with copies while changing one value. That's why records fit DTOs, messages and events. Positional properties are immutable in a record class and a readonly record struct, but mutable in a record struct; for a small value with no identity, like a coordinate or an amount, the safe form is readonly record struct.

Choosing between the two works like choosing between a class and a struct. One limit catches people off guard: a record can inherit from another record, but not from a regular class, and a class can't inherit from a record. If your DTO has to derive from a base that isn't a record, it can't be a record.

Partial, generic, nested and file: traits that combine

Partial

partial doesn't create a different type: it splits the declaration into parts that the compiler merges. Its natural use is keeping your code apart from what a source generator produces. C# 13 added partial properties and indexers, and C# 14 added partial constructors and events, which take exactly one defining declaration and one implementing declaration; only the implementing one can call this() or base().

// Report.Definition.cs: the declaring part (a source generator would write it).
public partial class Report
{
    public string Title { get; }

    public partial Report(string title); // C# 14: partial constructor, no body
}
// Report.Implementation.cs: the implementing part.
public partial class Report
{
    public partial Report(string title)
    {
        ArgumentException.ThrowIfNullOrWhiteSpace(title);
        Title = title;
    }

    public override string ToString() => $"Report: {Title}";
}

What doesn't pay off is using partial to "tidy up" a huge class across several files: it's just as big, only harder to notice.

Generic

A generic class takes type parameters and narrows them with constraints, such as where TKey : notnull. Unlike Java, C# doesn't erase types: the full type information exists at run time.

public class Cache<TKey, TValue> where TKey : notnull
{
    private readonly Dictionary<TKey, TValue> _items = new();

    public TValue Get(TKey key, Func<TKey, TValue> create)
    {
        if (!_items.TryGetValue(key, out var value))
        {
            value = create(key);
            _items[key] = value;
        }
        return value;
    }

    public int Count => _items.Count;
}

If Cache<int, string> is the only one in use, the type parameter is complexity with no payoff.

Nested

A nested type is private by default and can access every member of its container, private ones included. It's the place for a helper that only makes sense inside one class:

public class Cart
{
    private readonly List<Line> _lines = [];

    public void Add(string product, int quantity) => _lines.Add(new Line(product, quantity));

    public int Units => _lines.Sum(l => l.Quantity);

    // Nested and private: outside Cart it doesn't exist.
    private sealed record Line(string Product, int Quantity);
}

If you make a nested type public, it breaks rule CA1034 (off by default, like CA1852), usually a sign it should be a top-level type.

file (C# 11)

file limits a top-level type's visibility to the file that declares it. Source generators apply it mostly to the types they generate, but it works by hand too:

// file: visible only in this file.
file sealed class Format
{
    public static string Money(decimal amount) =>
        amount.ToString("0.00", System.Globalization.CultureInfo.InvariantCulture);
}

public static class Output
{
    public static string Money(decimal amount) => Format.Money(amount);
}

A file type can't be the return type or a parameter type of any member of a type that isn't file: if Output.Money returned a Format, the compiler would report CS9051.

What's new in C# 14 for classes

Besides extension members and partial constructors, C# 14 brings field: inside an accessor, it reaches the backing field the compiler synthesizes, without declaring it. All three features are stable: we tested them on net10.0, and none compiles with LangVersion 13.

public class Product
{
    public string Name
    {
        get;
        set => field = string.IsNullOrWhiteSpace(value)
            ? throw new ArgumentException("The name can't be empty.", nameof(value))
            : value.Trim();
    } = "";
}

var product = new Product { Name = "  Keyboard  " };
Console.WriteLine($"'{product.Name}'"); // → 'Keyboard'
product.Name = " ";                     // → ArgumentException

Before, validating in the setter meant declaring a private field; now the get stays automatic. One warning: if the type already has a member named field, the keyword can change what the code means. Disambiguate with @field or this.field, or rename the member.

Which one to choose: a decision table

The diagram puts the questions in order; the table says when each option stops being a good fit.

How to choose a class type in C# 14 Decision diagram. If the type needs no instances, static class. If it is data compared by value, record, or readonly record struct when it is small and has no identity. If it only serves as a base for other classes, abstract class, or closed in C# 15; otherwise, sealed class. Each path is drawn in order. No Yes Yes Yes No No No Yes Does it need instances? Is it data compared by value? Small, with no identity? Is it only a base for other classes? static class readonly record struct record sealed class abstract class or closed, in C# 15 (preview) partial, generic, nested and file combine with any of these answers.
I need…UseWhyAvoid it if…
Objects with state and behavior, no planned inheritanceRegular class + sealedExplicit design; the JIT can devirtualizeYou ship a library others must extend
A base with shared code and required stepsabstract (with virtual where needed)Can't be instantiated and forces implementationThere's no shared state or code: an interface may do
Stateless functions, constants or extension membersstaticNo instances, sealed, hosts extension blocksYou need to swap it in tests or keep state
Immutable data compared by value (DTOs, messages, events)recordValue equality, with and ToStringIt must inherit from a class that isn't a record
A small value with no identity (coordinates, amounts)readonly record structValue type and immutableThe type is large or needs inheritance
Splitting a class between your code and a generatorpartialSeveral declarations, one type; partial constructors in C# 14You only want to break up a giant file
The same algorithm for many typesGeneric with constraintsType safety without castsOnly one concrete type is ever used
A helper used by a single classNested privatePrivate by default; sees the container's private membersOther code uses it (CA1034)
A helper used by a single file or a generatorfileInvisible outside the fileIt must appear in a public signature (CS9051)
A hierarchy with known children and an exhaustive switchclosed (C# 15)Only the same assembly can deriveToday, in production on .NET 10: it's preview
A value that is one of several types, with no hierarchyunion (C# 15)The switch covers the cases with no _ armSame as closed: it's preview

In an order service, the split looks like this: messages and DTOs as records, amounts as readonly record struct, domain entities as sealed classes, the notifier base as abstract, utilities and extensions as static, and generated code as partial.

Coming in C# 15 (preview)

Heads-up: C# 15 ships with .NET 11, at RC3 today, and may change before release. We tested it with SDK 11.0.100-rc.3 on a net11.0 project without touching LangVersion: C# 15 is the default for that TFM.

closed covers something people sometimes want from a sealed class: a hierarchy with known children. A closed class can only be derived from inside its own assembly, so the compiler knows its direct children and the switch can be exhaustive with no _ arm:

// C# 15 (preview): only this assembly can derive from Shape.
public closed class Shape;

public sealed class Circle(double radius) : Shape
{
    public double Radius => radius;
}

public sealed class Rectangle(double width, double height) : Shape
{
    public double Width => width;
    public double Height => height;
}

public static class Geometry
{
    // No _ arm: the compiler knows there are no other children.
    public static double Area(Shape shape) => shape switch
    {
        Circle c => Math.PI * c.Radius * c.Radius,
        Rectangle r => r.Width * r.Height,
    };
}
  • It's implicitly abstract (new Shape() is error CS0144) and can't be combined with sealed (CS9381), static or abstract.
  • If the switch misses a child, the compiler warns with CS8509.
  • Deriving from another assembly is error CS9382. A child that isn't closed can still have subclasses elsewhere; that's why the children in the example are sealed.

Union types represent a value that can be one of several types, without making them share a base:

// C# 15 (preview): a Payment is either Cash or a Card.
public record class Cash(decimal Amount);
public record class Card(string Last4);
public union Payment(Cash, Card);

public static class Billing
{
    public static string Describe(Payment payment) => payment switch
    {
        Cash c => $"cash {c.Amount}",
        Card k => $"card ****{k.Last4}",
    };
}

Another feature that touches classes is minor: extension blocks will accept indexers.

Frequently asked questions

Should I seal all my classes?

In an application, every class that wasn't designed for inheritance. In a public library, only the ones nobody should extend. For internal types, turn on CA1852.

record or class for a DTO?

record, if it's compared by value and copied with with. class, if it has to inherit from a base that isn't a record, or if two objects with the same data must stay distinct.

What's the difference between a static class and a sealed class?

A sealed class can be instantiated, but nobody can inherit from it. A static class can't be instantiated and, being sealed already, doesn't allow inheritance either. abstract sealed is error CS0418: a class can't be only a base and also forbid inheritance.

Conclusion

Choosing a class type in C# is answering three questions, not picking one of eight. In C# 14, the default answer for an application class is sealed; data compared by value is a record or a readonly record struct; and extension members, partial constructors and field remove boilerplate.

A concrete first step: turn on CA1852 in your solution's .editorconfig. It's one line, and it hands you the list of internal classes nobody inherits from. When .NET 11 leaves preview, try closed on the first hierarchy you now handle with a switch and a filler _ arm.

References

Subscribe

Get the latest posts delivered right to your inbox.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Comments

No comments yet. Be the first to share your thoughts!

Subscribed!

Registered! A confirmation link has been sent to your email address. If you don't see it, please check your spam folder.

Error

An error occurred. Please try again.

Full code