Command Pattern Implementation in C#
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 this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Command Pattern runs in O(1) time and O(n) space, in C# as in every other language.
- ✓ICommand in System.Windows.Input is a framework interface, not merely a pattern: it declares Execute, CanExecute and the CanExecuteChanged event, and WPF, MAUI and Uno bind a button directly to it so the button enables and disables itself.
- ✓Use the RelayCommand source generator rather than hand-writing an ICommand class; reviewers expect it and hand-written versions usually get CanExecuteChanged wrong.
- ✓The C# trap: CanExecuteChanged is where hand-written commands break. If it is never raised, the button stays permanently disabled or permanently enabled and the bug looks like a binding problem.
- ✓Each command invocation through ICommand is an interface call plus a boxing of the parameter, which is irrelevant at UI rates and matters in a bus processing millions of messages, where a generic struct handler avoids both.
What Command Pattern actually is
Command Pattern in C#: what you actually reach for
C# implementation
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
public partial class EditorViewModel : ObservableObject
{
[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(SaveCommand))] // raises CanExecuteChanged for us
private string text = "";
private string? previous;
[RelayCommand(CanExecute = nameof(CanSave))]
private void Save()
{
previous = Text; // snapshot for undo
}
private bool CanSave() => !string.IsNullOrWhiteSpace(Text);
[RelayCommand]
private void Undo()
{
if (previous is not null) Text = previous;
}
// Async command: re-entrancy blocked and the button disables while it runs.
[RelayCommand]
private async Task PublishAsync(CancellationToken ct)
{
await Task.Delay(500, ct);
}
}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 FreeThe C#-specific trap
Performance in C#, beyond the O(1)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which C# type or library should I use for Command Pattern?
ICommand in System.Windows.Input is a framework interface, not merely a pattern: it declares Execute, CanExecute and the CanExecuteChanged event, and WPF, MAUI and Uno bind a button directly to it so the button enables and disables itself. CommunityToolkit.Mvvm generates the implementation from a RelayCommand attribute on a method, including the async variant with its own cancellation. For queues, System.Threading.Channels is the modern producer-consumer primitive and IHostedService hosts the worker.
What is the most common C# mistake when implementing Command Pattern?
CanExecuteChanged is where hand-written commands break. If it is never raised, the button stays permanently disabled or permanently enabled and the bug looks like a binding problem. The classic WPF implementation routes it through CommandManager.RequerySuggested, which fires on nearly every UI event and re-evaluates every command in the window, so a costly CanExecute becomes a frame-rate problem; but subscribing to it directly and storing the handler in a field creates a strong reference from a static event to the view model, which is a textbook memory leak. The toolkit implementation exists because both halves of this are easy to get wrong.
How does Command Pattern actually perform in C#?
Each command invocation through ICommand is an interface call plus a boxing of the parameter, which is irrelevant at UI rates and matters in a bus processing millions of messages, where a generic struct handler avoids both. CommandManager.RequerySuggested re-runs every CanExecute on the visual tree whenever focus or input changes, so keeping CanExecute to a field comparison rather than a query is the practical rule. Channel<T> with a bounded capacity gives back-pressure without the thread blocking that BlockingCollection imposes. Time complexity is O(1) and space is O(n).
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 trialStudying for this? GitHub Copilot free tiers and academic plans are laid out on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
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.