Decorator 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
- ✓Decorator Pattern runs in O(1) time and O(n) space, in C# as in every other language.
- ✓The object decorator is a class implementing the same interface and holding the inner instance, and System.IO is built on it exactly as java.io is: BufferedStream, GZipStream and CryptoStream all wrap another Stream.
- ✓Write the decorator as a sealed class implementing the interface, take the inner instance through the constructor, and register the chain in the DI container, most containers support decorator registration directly, and Scrutor adds a Decorate extension for the built-in one.
- ✓The C# trap: Attributes do NOT execute. Writing [Cache] or [Retry] above a method changes nothing at all unless some framework reflects over it and acts, and because the code compiles and looks declarative, the silent no-op survives review, this is the single most common C# misunderstanding of the pattern.
- ✓A hand-written decorator is a virtual call the JIT devirtualises and inlines when the chain is monomorphic, so static decorator stacks are effectively free.
What Decorator Pattern actually is
Decorator Pattern in C#: what you actually reach for
C# implementation
using System;
using System.IO;
using System.IO.Compression;
public interface IStore
{
string? Get(string key);
void Set(string key, string value);
}
// Decorator: same interface, inner injected, only Get changes.
public sealed class TimedStore : IStore
{
private readonly IStore _inner;
public TimedStore(IStore inner) => _inner = inner;
public string? Get(string key)
{
var t0 = System.Diagnostics.Stopwatch.GetTimestamp();
try { return _inner.Get(key); }
finally { Console.WriteLine($"{key} {System.Diagnostics.Stopwatch.GetElapsedTime(t0)}"); }
}
public void Set(string key, string value) => _inner.Set(key, value);
}
public static class Files
{
public static void Write(string path, byte[] data)
{
// Dispose the OUTERMOST only; it cascades and flushes.
using var file = File.Create(path);
using var gzip = new GZipStream(file, CompressionMode.Compress);
using var buffered = new BufferedStream(gzip);
buffered.Write(data);
}
}
// [Cache] / [Retry] attributes DO NOTHING on their own. An attribute is
// inert metadata; without a framework reflecting over it and building a
// proxy, the annotated method is completely unchanged.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 Decorator Pattern?
The object decorator is a class implementing the same interface and holding the inner instance, and System.IO is built on it exactly as java.io is: BufferedStream, GZipStream and CryptoStream all wrap another Stream. For interception without hand-written forwarding, System.Reflection.DispatchProxy generates a proxy over an interface at runtime. ATTRIBUTES are the thing people mistake for decorators and are not: they are inert metadata.
What is the most common C# mistake when implementing Decorator Pattern?
Attributes do NOT execute. Writing [Cache] or [Retry] above a method changes nothing at all unless some framework reflects over it and acts, and because the code compiles and looks declarative, the silent no-op survives review, this is the single most common C# misunderstanding of the pattern. The second trap mirrors Java: disposing an inner stream instead of the outer one loses buffered bytes silently. Third, a decorator that implements IDisposable must decide whether it owns the inner instance, and getting that wrong produces either a leak or an ObjectDisposedException from a second consumer.
How does Decorator Pattern actually perform in C#?
A hand-written decorator is a virtual call the JIT devirtualises and inlines when the chain is monomorphic, so static decorator stacks are effectively free. DispatchProxy routes every call through Invoke with a boxed object[] of arguments, which allocates per call and defeats inlining, comparable to Java dynamic proxies and appropriate only at coarse granularity. Interface dispatch through a DI-resolved chain is a few nanoseconds per layer. 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? Devin 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.