Template Engine 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
- ✓Template Engine runs in O(n) time and O(n) space, in C# as in every other language.
- ✓`System.Linq.Expressions` is what makes this a literally compiled template: build a tree of `TextWriter.Write` calls, then `Expression.Lambda<T>(...).Compile()` emits IL and returns a delegate that runs at ordinary method speed.
- ✓Cache a `Lazy<Plan>`, never the delegate on its own. `ConcurrentDictionary.GetOrAdd` explicitly does not promise the factory runs once: it runs outside the bucket lock, so a cold-start burst has several threads each building an expression tree and calling `Compile`, with all but one result discarded.
- ✓The C# trap: `Compile()` is not always compilation. Given a JIT it emits IL and hands back a real delegate.
- ✓After `Compile()` a render is one delegate invoke plus one `Write` per chunk, with literal chunks captured as constants in the tree rather than re-sliced each time.
What Template Engine actually is
Template Engine in C#: what you actually reach for
C# implementation
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq.Expressions;
using System.Net;
using System.Reflection;
public readonly record struct Raw(string Html); // the only opt-out
public delegate void Plan(TextWriter w, IReadOnlyDictionary<string, object> d);
public static class Board
{
private static readonly MethodInfo Wr = typeof(TextWriter).GetMethod("Write", new[] { typeof(string) })!;
// The cached value is a Lazy, not the delegate: GetOrAdd runs its factory outside
// the bucket lock, so a bare one lets several threads compile the same template.
private static readonly ConcurrentDictionary<string, Lazy<Plan>> Plans = new();
public static string Encode(object v) =>
v is Raw r ? r.Html : WebUtility.HtmlEncode(v?.ToString() ?? "");
private static Plan Compile(string src)
{
var w = Expression.Parameter(typeof(TextWriter), "w");
var d = Expression.Parameter(typeof(IReadOnlyDictionary<string, object>), "d");
Expression Write(Expression arg) => Expression.Call(w, Wr, arg);
var body = new List<Expression>();
int pos = 0, open;
while ((open = src.IndexOf("{{", pos, StringComparison.Ordinal)) >= 0)
{
int close = src.IndexOf("}}", open + 2, StringComparison.Ordinal);
if (close < 0) break;
if (open > pos) body.Add(Write(Expression.Constant(src[pos..open])));
var key = Expression.Constant(src[(open + 2)..close].Trim());
body.Add(Write(Expression.Call(typeof(Board), nameof(Encode), null,
Expression.Property(d, "Item", key))));
pos = close + 2;
}
if (pos < src.Length) body.Add(Write(Expression.Constant(src[pos..])));
return Expression.Lambda<Plan>(Expression.Block(body), w, d).Compile();
}
public static string Render(string src, IReadOnlyDictionary<string, object> data)
{
Plan plan = Plans.GetOrAdd(src, static s => new Lazy<Plan>(() => Compile(s))).Value;
using var sw = new StringWriter();
plan(sw, data);
return sw.ToString();
}
}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(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which C# type or library should I use for Template Engine?
`System.Linq.Expressions` is what makes this a literally compiled template: build a tree of `TextWriter.Write` calls, then `Expression.Lambda<T>(...).Compile()` emits IL and returns a delegate that runs at ordinary method speed. `System.Net.WebUtility.HtmlEncode` is the BCL encoder, `StringWriter` or `StringBuilder` is the sink, `System.Collections.Concurrent.ConcurrentDictionary` holds the compiled plans, and `System.Reflection.MethodInfo` supplies the `Write(string)` handle the tree needs. Razor is the framework-level answer and takes the opposite route, generating C# source ahead of time.
What is the most common C# mistake when implementing Template Engine?
`Compile()` is not always compilation. Given a JIT it emits IL and hands back a real delegate. On any runtime without one, an iOS build or a NativeAOT publish, there is nothing to hand the emitted method to and the identical call falls back to the expression interpreter; the explicit spelling of that is `Compile(preferInterpretation: true)`. Your compiled template quietly becomes a tree walk again, with no exception, no warning and no build error, and the entire justification for the design evaporates. Branch on `RuntimeFeature.IsDynamicCodeCompiled` and keep a hand-written closure plan as the fallback.
How does Template Engine actually perform in C#?
After `Compile()` a render is one delegate invoke plus one `Write` per chunk, with literal chunks captured as constants in the tree rather than re-sliced each time. The costs sit elsewhere. `Compile()` walks the tree, emits a dynamic method and pays a JIT on first invoke, orders of magnitude more than a render, which is exactly why the plan must be cached. `WebUtility.HtmlEncode` returns the original reference when nothing needed encoding, so clean fields do not allocate. And `Expression.Property(d, "Item", ...)` compiles to an interface call, so typing the parameter as a concrete `Dictionary<string, object>` removes one virtual dispatch per hole. Time complexity is O(n) 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 trialBefore paying for GitHub Copilot, 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.