How-to guides
Write a rule in C#
Updated 3 November 2026 · 2 min read
Most values in a model are one formula. Some are a rule: a tiered price, a treatment policy that switches at a threshold, a controller that only acts outside a band. A C# block is a variable you work out with C# of your own, with ifs, loops and local variables.
Add one#
Click C# Block in the components list and place it. It is drawn dark on the canvas, so code stands out from formulas. Select it and write the code in the side panel, ending in a return.
- 1The function your code is the body of: time, and every value your code reads.
- 2Your C#. It must end by returning the value.
What the code can use#
t, the time.- Any stock, constant or variable, by its name in formulas.
- Your lookup tables, called like functions.
Exp,Log,Pow,Sqrt,Min,MaxandAbs, as in formulas.- Local variables,
ifandelse, and loops. - Anything else from C#’s maths library written in full, as
System.Math.Round: SepalSolver has aMathof its own, so a bareMathis ambiguous and won’t compile.
You don’t declare what the block reads. The builder finds the names in your code and passes their values in each time the model needs the block. The signature above the code shows what it found: double Bill(double t, double WaterUsed, double LowPrice, double HighPrice). Press Ctrl Enter to apply the code and run.
A worked example#
Water is billed at 1.50 $/m³ for the first 100 m³ and 3.00 $/m³ after that. A household uses 4 m³ a day. The bill is a rule with two branches, which is exactly what a block is for:
// the first 100 m³ at the low price, the rest at the high price
if (WaterUsed <= 100) return WaterUsed * LowPrice;
return 100 * LowPrice + (WaterUsed - 100) * HighPrice;
On day 25 the household has used 100 m³ and the bill is $150. By day 60 it has used 240 m³, and the bill is 150 + 140 × 3 = $570. The bill’s slope doubles on day 25, which is the whole point of a tiered tariff.
When not to use one#
If the rule is a threshold, a formula usually says it more plainly: Step(t - 10) switches something on at time 10, and Min and Max hold a value within limits. Reach for a block when the formula would need nested Mins and Steps to say what an if says in one line.
See also
- C# blockA variable worked out by C# you write.
- FormulasWhat a formula can contain: names, t, operators and functions.
- Read and run the C# behind a modelThe program SepalSolver runs, and how to take it to the terminal and change it.
- Use a curve from data in a formulaDraw or paste a relationship you know from data, and call it like a function.