Template Method 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 your Design Patterns question into a ready to paste AI prompt, free →
Key Takeaways
- ✓Template Method Pattern runs in O(1) time and O(1) space, in C# as in every other language.
- ✓An abstract class with a non-virtual template method and abstract or virtual steps, which is the direct equivalent of the Java form; sealed override stops further overriding partway down a hierarchy.
- ✓Leave the template method non-virtual, which in C# means simply not marking it virtual, so it cannot be overridden without the explicit and warned-about new keyword.
- ✓The C# trap: A default interface method is only callable through the INTERFACE, not through the implementing class: a class implementing the interface does not inherit the member into its own public surface, so calling it on a variable typed as the class fails to compile and calling it on the same object typed as the interface works.
- ✓Virtual step calls go through the method table; the JIT devirtualises when it can prove a single implementation, and with dynamic PGO in recent .NET versions it can also do so speculatively based on observed types, which makes the template pattern cheaper than it used to be.
What Template Method Pattern actually is
Template Method Pattern in C#: what you actually reach for
C# implementation
public abstract class Importer<T>
{
// Non-virtual: a subclass cannot override the algorithm (only HIDE it with 'new').
public int Run(string path)
{
var raw = Read(path);
var rows = Transform(raw);
After(rows);
return rows.Count;
}
protected abstract string Read(string path);
protected abstract IReadOnlyList<T> Transform(string raw);
protected virtual void After(IReadOnlyList<T> rows) { } // optional hook
}
public sealed class CsvImporter : Importer<string> // sealed: devirtualises
{
protected override string Read(string path) => "a,b\nc,d";
protected override IReadOnlyList<string> Transform(string raw) => raw.Split('\n');
}
// Default interface methods: callable through the INTERFACE only.
public interface IImporter
{
string Read(string path);
int Run(string path) => Read(path).Length; // the template, in an interface
}
public sealed class Simple : IImporter
{
public string Read(string path) => "abcd";
}
// new Simple().Run("x"); // compile error: Simple has no Run
// ((IImporter)new Simple()).Run("x"); // 4, works through the interfaceThink 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 Template Method Pattern?
An abstract class with a non-virtual template method and abstract or virtual steps, which is the direct equivalent of the Java form; sealed override stops further overriding partway down a hierarchy. Since C# 8, default interface methods allow the Rust and Swift shape as well: an interface can supply an implementation that calls its own members, so a template lives in an interface rather than a base class, which frees the implementor to inherit elsewhere.
What is the most common C# mistake when implementing Template Method Pattern?
A default interface method is only callable through the INTERFACE, not through the implementing class: a class implementing the interface does not inherit the member into its own public surface, so calling it on a variable typed as the class fails to compile and calling it on the same object typed as the interface works. That asymmetry surprises everyone once. The other trap is the new keyword: a derived class that redeclares a non-virtual template method with new HIDES rather than overrides it, so which implementation runs depends on the STATIC type of the reference, and the same object produces different behaviour through different variables.
How does Template Method Pattern actually perform in C#?
Virtual step calls go through the method table; the JIT devirtualises when it can prove a single implementation, and with dynamic PGO in recent .NET versions it can also do so speculatively based on observed types, which makes the template pattern cheaper than it used to be. Default interface methods dispatch through the interface method table and are not devirtualised as readily. Sealing a class or an override enables devirtualisation and is worth doing on leaf types. Time complexity is O(1) and space is O(1).
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 trialBefore paying for Devin, check its student and free-tier options 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.