Early previewThis guide is in development. Items tagged verify are still being checked against official docs.
nebx Learn
GitHub
Menu
C#

C#

A productive, strongly typed language for the whole .NET platform.

Paradigm
OOP, functional features
Typing
Static, strong, nullable-aware
Memory
Generational GC
Runs
.NET runtime (JIT) or Native AOT
Concurrency
Tasks, async/await, channels
Behavioral pattern

Command

Intent

Turns a request into a stand-alone object containing all information about the request.

Problem

Buttons, menu items and shortcuts all trigger “save”, and you need undo.

Solution

Wrap each action in a command object with execute (and undo); invokers just call execute.

Real-world analogy

Think of it like this

A restaurant ticket: the waiter writes your order down and the chef executes it later, in order.

Structure

association / extends implements / depends on
Invoker - command+ setCommand(c)+ executeCommand() 1 «interface» Command + execute() 2 ConcreteCommand - receiver- params+ execute() 3 Receiver + operation(a, b, c) 4 Client 5

Hover or tap a numbered role to highlight it in the diagram.

  1. 1Invoker — Invoker (sender) triggers the command instead of calling the receiver directly.
  2. 2Command — Command declares a single execution method.
  3. 3ConcreteCommand — Concrete Commands store parameters and pass the call to a receiver.
  4. 4Receiver — Receiver contains the actual business logic.
  5. 5Client — Client creates and configures commands, then hands them to invokers.

Code example

A C# code sample for Command is coming soon. Factory Method, Singleton, Decorator, Observer and Strategy already have code in all six languages.

Applicability

Use Command when parameterising objects with operations.

Use Command when queuing, scheduling or remote execution.

Use Command when undo / redo.

Pros and cons

Pros

  • Decouples invokers from receivers
  • Undo / redo, deferred execution, composite commands

Cons

  • An extra layer between senders and receivers

Check yourself

Check yourself

A drawing app needs undo / redo for every user action and a macro recorder.

Saved in this browser only. Part of Behavioral patterns (0/11).