Tutorials Design Patterns in C#
Interpreter Pattern — Complete Guide
Interpreter Pattern — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of Design Patterns in C# on Toolliyo Academy.
On this page
Design Patterns in C# · Lesson 15 of 69
Interpreter Pattern
GoF Core ✓ → Enterprise → Cloud & Craft
Enterprise · 2 — App patterns · ~6 min · Module 3: Behavioral Design Patterns
What is this?
Interpreter defines a grammar and an evaluator for a simple language — useful for rules engines, not general programming languages.
Why should you care?
ShopNest promo rules like “SKU starts with HD and price > 1000” need a tiny expression tree.
See it live — copy this example
Paste into a C# console or class library project and run dotnet run.
public interface IRule { bool Eval(Item item); }
public sealed record Item(string Sku, decimal Price);
public sealed class SkuPrefixRule : IRule
{
private readonly string _prefix;
public SkuPrefixRule(string p) => _prefix = p;
public bool Eval(Item i) => i.Sku.StartsWith(_prefix);
}
public sealed class MinPriceRule : IRule
{
private readonly decimal _min;
public MinPriceRule(decimal m) => _min = m;
public bool Eval(Item i) => i.Price >= _min;
}
public sealed class AndRule : IRule
{
private readonly IRule _a, _b;
public AndRule(IRule a, IRule b) { _a = a; _b = b; }
public bool Eval(Item i) => _a.Eval(i) && _b.Eval(i);
}
IRule promo = new AndRule(new SkuPrefixRule("HD"), new MinPriceRule(1000));
Console.WriteLine(promo.Eval(new Item("HD-100", 4999)));
Run Example »
Edit the code below and click Run to see the result in Toolliyo’s live editor.
What happened?
- Leaf rules check one fact; AndRule composes them.
- That is a tiny interpreter over a rule AST.
- For complex grammars prefer a mature library.
Practice next
- Evaluate the sample item true/false.
- Add OrRule.
- Parse a simple string into rules later.
- Add NotRule.
- Fail HD-50 at price 500.
Remember
AST + Eval. Compose rules. Keep scope tiny.
ShopNest promo rule tree
Marketing composes prefix + min-price rules.
Outcome: Promos change without redeploying ifs everywhere.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!