Skip to contentSaltar al contenido
125+ QA and SEO checks per page

CQRS Pattern Implementation in C#

19 min readadvanced
Website QA and SEO audits

14-day free trial

Try SeekerPro free for 14 days.

Full access while you try it · then $15.99/mo · cancel anytime

Start your 14-day free SeekerPro trial →

30-day money-back guarantee · Cancel anytime

Not checking a site today? Turn your Database Patterns question into a ready to paste AI prompt, free →

Key Takeaways

  • ✓CQRS Pattern runs in O(1) time and O(n) space, in C# as in every other language.
  • ✓Records arrived in C-sharp 9 and give value-based equality and non-destructive copying through with expressions, and switch expressions give pattern matching over a type hierarchy.
  • ✓Declare an abstract record base with the commands as nested records, and dispatch with a switch expression using type patterns.
  • ✓The C# trap: C-sharp has no exhaustiveness checking over a type hierarchy, which is the one place it falls behind Java 21, Rust and Swift on this pattern.
  • ✓Type-pattern switches compile to a sequence of type checks, so the cost grows with the number of cases, unlike the jump table an enum-based dispatcher produces in Rust or Swift.

What CQRS Pattern actually is

Command Query Responsibility Segregation splits the model that changes state from the model that answers questions. A command expresses an intent, mutates something and returns nothing beyond success or failure; a query returns data and is forbidden to change anything. Once that line is drawn you can optimise the two halves independently, which is the real payoff: the write side can be normalised and transactional while the read side is denormalised and shaped exactly like the screen that displays it. The pattern is mostly discipline rather than machinery, so the interesting difference between languages is how much of that discipline the compiler can enforce. Three of these eight can prove at compile time that you have handled every command you defined; one of them throws at run time instead; and the rest rely entirely on review.

CQRS Pattern in C#: what you actually reach for

Records arrived in C-sharp 9 and give value-based equality and non-destructive copying through with expressions, and switch expressions give pattern matching over a type hierarchy. MediatR is the near-universal library, though nothing in the pattern requires it.

C# implementation

Declare an abstract record base with the commands as nested records, and dispatch with a switch expression using type patterns. Add a discard arm that throws a domain-specific exception so the run-time hole is at least explicit.
csharp
using System;
using System.Collections.Generic;

public abstract record Command
{
    // A private constructor approximates sealing: outside code cannot add
    // a subtype. It still does NOT give the compiler exhaustiveness.
    private Command() { }

    public sealed record CreateOrder(Guid OrderId, IReadOnlyList<string> Items) : Command;
    public sealed record CancelOrder(Guid OrderId, string Reason) : Command;
    public sealed record ShipOrder(Guid OrderId, string Carrier) : Command;
}

public abstract record DomainEvent
{
    private DomainEvent() { }

    public sealed record OrderCreated(Guid OrderId, IReadOnlyList<string> Items) : DomainEvent;
    public sealed record OrderCancelled(Guid OrderId, string Reason) : DomainEvent;
    public sealed record OrderShipped(Guid OrderId, string Carrier) : DomainEvent;
}

public static class Handler
{
    /// <summary>
    /// C# has NO exhaustiveness check over a type hierarchy. An uncovered
    /// case compiles with at most a warning and throws
    /// SwitchExpressionException at RUN TIME, the failure Java 21, Rust
    /// and Swift catch at build time happens here in production.
    /// The discard arm is therefore mandatory, and it should throw
    /// something searchable rather than the framework's own exception.
    /// </summary>
    public static DomainEvent Handle(Command command) => command switch
    {
        Command.CreateOrder(var id, var items) => new DomainEvent.OrderCreated(id, items),
        Command.CancelOrder(var id, var reason) => new DomainEvent.OrderCancelled(id, reason),
        Command.ShipOrder(var id, var carrier) => new DomainEvent.OrderShipped(id, carrier),
        _ => throw new NotSupportedException($"unhandled command {command.GetType().Name}"),
    };
}

// Record equality is synthesised and compares EVERY field, and a
// collection field is compared by REFERENCE, not by contents. Two
// CreateOrder records with equal-looking item lists are not equal.

Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.

Paste your code. Click QA. Get an instant expert-level audit with fixes.

QA My Code Free

The C#-specific trap

C-sharp has no exhaustiveness checking over a type hierarchy, which is the one place it falls behind Java 21, Rust and Swift on this pattern. A switch expression that does not cover every case compiles with at most a warning and throws SwitchExpressionException at run time when an unmatched value arrives, so the failure that the other three catch at build time happens here in production. Making the base record abstract with a private constructor approximates sealing, in that outside code cannot add a subtype, but the compiler still will not verify that your switch covers the ones that exist. Treat the discard arm as mandatory and make it throw something you can search for. Also note that record equality is synthesised and compares every field, so a command holding a large collection is expensive to compare and the collection is compared by reference, not by contents.

Performance in C#, beyond the O(1)

Type-pattern switches compile to a sequence of type checks, so the cost grows with the number of cases, unlike the jump table an enum-based dispatcher produces in Rust or Swift. Records are reference types by default; record struct is available when you want the command on the stack. The asymptotic cost is the same in every language, O(1) time and O(n) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port CQRS Pattern between languages.

Real-World Applications

CQRS Pattern is used extensively in production software: relational databases, NoSQL systems, ORMs, and data pipelines use this pattern for managing data access and consistency. In C# specifically, .NET, Entity Framework, and ASP.NET Core use these patterns. Understanding CQRS Pattern helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

CQRS Pattern appears frequently in final rounds at FAANG-level companies and system design interviews. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose CQRS Pattern over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of CQRS Pattern to build pattern recognition. In C#, demonstrate proficiency with LINQ and async patterns to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic C# code that is both correct and maintainable.

Frequently Asked Questions

Which C# type or library should I use for CQRS Pattern?

Records arrived in C-sharp 9 and give value-based equality and non-destructive copying through with expressions, and switch expressions give pattern matching over a type hierarchy. MediatR is the near-universal library, though nothing in the pattern requires it.

What is the most common C# mistake when implementing CQRS Pattern?

C-sharp has no exhaustiveness checking over a type hierarchy, which is the one place it falls behind Java 21, Rust and Swift on this pattern. A switch expression that does not cover every case compiles with at most a warning and throws SwitchExpressionException at run time when an unmatched value arrives, so the failure that the other three catch at build time happens here in production. Making the base record abstract with a private constructor approximates sealing, in that outside code cannot add a subtype, but the compiler still will not verify that your switch covers the ones that exist. Treat the discard arm as mandatory and make it throw something you can search for. Also note that record equality is synthesised and compares every field, so a command holding a large collection is expensive to compare and the collection is compared by reference, not by contents.

How does CQRS Pattern actually perform in C#?

Type-pattern switches compile to a sequence of type checks, so the cost grows with the number of cases, unlike the jump table an enum-based dispatcher produces in Rust or Swift. Records are reference types by default; record struct is available when you want the command on the stack. Time complexity is O(1) and space is O(n).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

Related Articles

Rather try before you buy?

Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.

Start my 14-day SeekerPro trial

Before paying for Devin, check its student and free-tier options on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Want 50 audits a day? Explore SeekerPro

Engagement

0

Reader comments

No account needed. Share what worked, what did not, and what you would add.

Add your take below. A concrete tip, a result or a question helps the next reader most.