TagBites.Expressions
TagBites.Expressions is a Roslyn-based C# expression parser and evaluator for .NET.
It compiles runtime string expressions into strongly typed Func<> delegates or LambdaExpression expression trees, without creating a new assembly.
var options = new ExpressionParserOptions { Parameters = { (typeof(int), "a"), (typeof(int), "b") } };var func = ExpressionParser.Compile<Func<int, int, int>>("(a + b) / 2", options);int r = func(2, 4); // 3Because Roslyn does the parsing, expressions use real C# syntax: operators, precedence, numeric promotion, implicit conversions, pattern matching, tuples, lambdas, LINQ and generics behave like they do in the C# compiler. If C# accepts the expression, TagBites.Expressions accepts it; if C# rejects it, so does the parser.
Try it online - type an expression and evaluate it in the browser.
Install
Section titled “Install”dotnet add package TagBites.ExpressionsTargets netstandard2.0. Only dependency is Microsoft.CodeAnalysis.CSharp.
Evaluate once:
ExpressionParser.Invoke("5 / 2.5"); // 2dExpressionParser.Invoke<int>("new [] { 1, 2, 3 }.Sum()"); // 6ExpressionParser.Invoke<int>("(a + b) / 2", ("a", 2), ("b", 4)); // 3Compile once, run many times:
var options = new ExpressionParserOptions { Parameters = { (typeof(double), "x"), (typeof(double), "y") } };var func = ExpressionParser.Compile<Func<double, double, double>>("Math.Pow(x, y) + 5", options);func(2, 10); // 1029func(2, 2); // 9Bind an object as this:
var options = new ExpressionParserOptions{ Parameters = { (typeof(TestModel), "this") }, UseFirstParameterAsThis = true};
ExpressionParser.Invoke("X + Y", options, new TestModel { X = 1, Y = 2 }); // 3Expose named values and delegates with GlobalMembers:
var options = new ExpressionParserOptions{ Parameters = { (typeof(int), "a") }, GlobalMembers = { { "b", (null, 2) } }};
var func = ExpressionParser.Compile<Func<int, int>>("a switch { 1 => b, 2 => b * 2, _ => b + a }", options);func(3); // 5Import static classes, as if using static was applied:
var options = new ExpressionParserOptions { StaticImports = { typeof(Math) } };
ExpressionParser.Invoke<double>("Sqrt(Max(9, 16)) + PI", options); // 7.14159...String interpolation, including alignment and format specifiers (formatting follows the current culture):
ExpressionParser.Invoke(@"$""sum = {1 + 2}"""); // sum = 3ExpressionParser.Invoke(@"$""{5,-4}|"""); // "5 |" (left aligned)ExpressionParser.Invoke(@"$""{5,6:000}"""); // " 005" (alignment + format)ExpressionParser.Invoke(@"$""{255:X}"""); // FFExpressionParser.Invoke(@"$""{new DateTime(2021, 8, 14):yyyy-MM-dd}"""); // 2021-08-14ExpressionParser.Invoke(@"$""{(1 < 2 ? ""yes"" : ""no"")}"""); // yesAnonymous objects (new { ... }) work like a real anonymous type without generating a new one, by internally mapping it to DynamicObject:
var script = "new[] { 1, 2, 3 }.Select(v => new { Value = v, Doubled = v * 2 }).Sum(v => v.Value + v.Doubled)";dynamic result = ExpressionParser.Invoke(script);Console.WriteLine(result); // 18Get the expression tree, or parse without throwing:
LambdaExpression lambda = ExpressionParser.Parse("x * 2 + 1", options);
if (!ExpressionParser.TryParse("a + ", options, out var expr, out var error)) Console.WriteLine(error);Use cases
Section titled “Use cases”Use TagBites.Expressions when you need to parse, validate, evaluate or compile C# expressions from strings at runtime:
- dynamic business rules and predicates
- user-defined formulas and calculations
- configurable filters and scoring logic
- compile-once/run-many
Func<>delegates LambdaExpressiontrees for expression-based APIs- LINQ-style runtime logic with real C# expression syntax
Why TagBites.Expressions?
Section titled “Why TagBites.Expressions?”- Real C# expression syntax - parsed by Roslyn, not by a custom C#-like grammar.
- Runtime expression evaluation - evaluate once or compile once and invoke many times.
- Delegates or expression trees - compile to
Func<>delegates or parse toLambdaExpression. - Modern C# expressions - supports LINQ, lambdas, pattern matching, switch expressions, tuples, generics, interpolated strings, etc.
- No generated assembly - expressions are compiled without creating a new assembly.
Supported C# expression syntax
Section titled “Supported C# expression syntax”- Operators: arithmetic, bitwise, shifts, comparison,
&& || !,?:,??,?./?[],is/as,x!. - User-defined operator overloads and user-defined implicit/explicit conversions.
- Literals: all numeric types,
char,string, verbatim, raw and interpolated strings, hex, digit separators. - Members and calls: properties, fields, indexers (including index-from-end
x[^1]), generic and extension methods,params. - Named arguments (
Method(digits: 2, value: 1)), including reordering, mixing positional and named arguments, and skipping optional parameters. new: constructors, object initializers (including index initializers["key"] = value), collection initializers, arrays (jagged, multidimensional including implicitly typednew[,], and sized), target-typednew()(including as a method or constructor argument).- Anonymous objects (
new { X = 1, Y = 2 }- see Usage above). - Lambdas and LINQ (
Select,Where,GroupBy, …), including nested and multi-argument lambdas. - Tuples, including named elements (
(Name: "Bob", Age: 30).Name) and element-wise equality. typeof,default(T), the baredefaultliteral (target-typed),nameof,sizeof,checked,unchecked.- Pattern matching in
isandswitch: type, constant, relational,and/or/not, property (including extended{ A.B: 1 }), positional,varand list patterns,whenguards. throwexpressions in?:and??(x > 0 ? x : throw new ArgumentException()), opt-in via theAllowThrowExpressionsoption.
Not currently supported:
- LINQ query syntax (
from x in items where x > 1 select x) - use the method syntax (items.Where(x => x > 1)). - The range operator (
1..2,arr[1..^1]). - Method group conversion as an argument (
items.Select(int.Parse)) - use a lambda (items.Select(x => int.Parse(x))). - Tuple types in a type position (
default((int, int)),new (int A, int B)[] { ... }) - name the elements through values instead. - The unsigned right-shift operator
>>>- depends on theMicrosoft.CodeAnalysis.CSharpversion the parser is built against.
Not supported:
- Statements (like
if),async/await, and declarations (methods, types) are out of scope - this is an expression parser. - Compound assignment and increment/decrement (
x += 1,x++,--x,??=) - this is an expression parser, expressions don’t mutate variables. ref/outarguments, includingout vardeclarations (e.g.int.TryParse(s, out var n)).
Supported expressions examples
Section titled “Supported expressions examples”// Switch expression1 switch { 1 => 10, 2 => 20, _ => 0 }
// Switch expression with a `when` guard5 switch { 5 when 1 > 2 => 1, 5 => 2, _ => 0 }
// Relational and logical patterns5 is > 0 and < 10
// List pattern with a slicenew[] { 1, 2, 3 } is [1, .., 3]
// Tuple deconstruction pattern(1, 2) is (int a, int b) && a < b
// Property pattern"ab" is { Length: 2 }
// Target-typed new() in nested collection initializersnew List<List<int>> { new() { 1, 2 }, new() { 3, 4 } }[1][0]
// Jagged arraynew int[][] { new[] { 1 }, new[] { 2, 3 } }[1][1] // 3
// Implicitly typed multidimensional arraynew[,] { { 1, 2 }, { 3, 4 } }[1, 0] // 3
// Dictionary index initializernew Dictionary<string, int> { ["a"] = 1, ["b"] = 2 }["b"] // 2
// Raw string literal"""hello world""".Length
// Digit separators1_000_000
// Index from endnew[] { 1, 2, 3 }[^1]
// Null-forgiving operator"a"!.Length
// Unchecked integer overflow, same wraparound as C#unchecked(2147483647 + 1)
// Generic method call with an explicit type argumentnew[] { 1, 2, 3 }.OfType<int>().Count()
// User-defined operator overload (DateTime.op_Addition / op_GreaterThan)DateTime.Now + TimeSpan.FromDays(1) > DateTime.Now
// Tuple equality(1, 2) == (1, 2)
// Tuple with named elements(Name: "Bob", Age: 30).Name
// Named arguments, reorderedMath.Round(digits: 2, value: 2.567)
// Bare default literal, target-typed from the other argumentMath.Max(default, 5)
// Anonymous object carrying a named tuple, combined with named args and lambdasnew[] { 1, 2, 3 } .Select(n => new { N = n, Stats = (Sum: n + n, Label: $"#{n}") }) .Where(x => x.Stats.Sum >= 4) .Select(x => Math.Round(digits: 0, value: (double)x.Stats.Sum) + x.Stats.Label.Length) .Sum() // 14Configuration
Section titled “Configuration”ExpressionParserOptions:
| Option | Purpose |
|---|---|
AllowReflection |
Allow reflection APIs. (default: false) |
AllowThrowExpressions |
Allow throw expressions in ?: and ??. (default: false) |
Parameters |
Typed parameters of the resulting lambda. |
UseFirstParameterAsThis |
Use the first parameter as this so its members need no prefix. |
GlobalMembers |
Named values and delegates usable by name; a member named this is implicit. |
IncludedTypes |
Types (and static classes) an expression may reference by name. |
IgnoreBuiltInTypes |
Disable the fixed set of common framework types otherwise available by short name, independent of IncludedTypes. (default: false) |
TypeResolver |
Fallback Func<string, Type?> that resolves a type from its name (optionally namespace-qualified) when it is not found elsewhere. |
StaticImports |
Imported static classes, as if using static was applied (e.g. Sqrt(x), PI). Parameters and global members take precedence. |
CustomPropertyResolver |
Resolve members at runtime, e.g. against types defined only at runtime. |
ResultType |
Require the result to be this type. An implicit conversion is applied if needed, otherwise parsing fails. |
ResultCastType |
Force the result to this type with an explicit cast, e.g. to compile every expression as Func<object>. |
UseMemberCache |
Cache reflected members (methods, indexers, extension methods) on this options instance; enable when reusing the same options across many parses. (default: false) |
CustomPropertyResolver:
It is only called for instance.Member, it needs an instance to work on. That can be an ordinary parameter, accessed explicitly - p.Age works for any parameter name. A bare name like Age also works, but it is then resolved implicitly as this.Age, so a this must be set up first: UseFirstParameterAsThis, or a this entry in GlobalMembers.
Result type:
ResultType is a contract: the expression must produce this type. A C# implicit conversion (like int -> long) is applied automatically; anything else is a parse error. Use it to require, for example, that a filter is a bool.
ResultCastType forces the return type with an explicit cast, so unrelated expressions can share one delegate signature. It also allows casts that are not implicit, such as double -> int.
The two combine: to run many rules through a single Func<object> while still requiring each to be boolean, set ResultType = typeof(bool) (reject anything non-boolean) together with ResultCastType = typeof(object).
Type resolution:
When an expression references a type by name (e.g. DateTime.Now, new List<int>(), (TimeSpan)x), the parser resolves it in this order: ResultType, Parameters, IncludedTypes, the built-in types, then TypeResolver.
By default a fixed set of common framework types is always available by short name, regardless of IncludedTypes:
- Time:
TimeSpan,DateTime,DateTimeOffset,DateTimeKind,DayOfWeek - Text:
StringComparison,StringSplitOptions - Math:
Math,MidpointRounding - Common:
Guid,KeyValuePair<,> - Collections:
Enumerable,List<>,Dictionary<,>,HashSet<>,IList<>,IEnumerable<>,ICollection<>,IReadOnlyList<>,IReadOnlyCollection<>,IDictionary<,>,IReadOnlyDictionary<,>,ISet<> - Other:
Convert,CultureInfo
Set IgnoreBuiltInTypes = true to make the parser accept only the types you explicitly allow. The C# primitive keywords (int, string, bool, object, …) are language keywords and are always available, independent of this option.
TypeResolver is a Func<string, Type?> fallback consulted last. It receives the type name, which may be namespace-qualified (for example System.Text.StringBuilder) or a short name, and returns the matching Type or null if it does not recognize the name. A generic type name is suffixed with an apostrophe and its type-argument count (for example List'1, Dictionary'2), and the resolver must return the open generic definition (typeof(List<>)); the parser closes it with the supplied type arguments.
var options = new ExpressionParserOptions{ TypeResolver = name => name switch { "StringBuilder" or "System.Text.StringBuilder" => typeof(StringBuilder), "ImmutableArray'1" => typeof(ImmutableArray<>), _ => null }};Reuse and immutability:
Like JsonSerializerOptions, an ExpressionParserOptions instance becomes read-only after it is first used for parsing, enabling fast concurrent use.
Fork:
Fork reuses the prepared, shared settings of an instance - global members, included types, static imports, the reflection member cache and the resolution flags - and overrides only the result type, parameters or this handling. Use it when one set of options is shared but different delegates must be produced from it, so the shared lookups are prepared once instead of per delegate.
var options = new ExpressionParserOptions { Parameters = { (typeof(int), "n") } };
var asLong = ExpressionParser.Compile<Func<int, long>>("n * 2", options.Fork(typeof(long)));var asObject = ExpressionParser.Compile<Func<int, object>>("n * 2", options.Fork(typeof(object)));
asLong(10); // 20LasObject(10); // 20 (boxed int)Non-standard options
Section titled “Non-standard options”These opt-in options (all default to false) make the parser accept syntax or semantics that real C# does not:
| Option | Purpose |
|---|---|
AllowStringRelationalOperators |
Allow < / <= / > / >= on strings, compared ordinally via string.Compare - not valid in real C#. |
AllowRuntimeCast |
Allow custom keywords typeis / typeas / typecast against runtime type names. |
IgnoreCase |
Resolve parameters, variables, global members, type members and IncludedTypes case-insensitively. For GlobalMembers/IncludedTypes, case-insensitive name collisions are checked before parsing. |
Advanced usage
Section titled “Advanced usage”FastExpressionCompiler
Section titled “FastExpressionCompiler”ExpressionParser.Parse() returns a plain LambdaExpression, so it can be compiled with any compiler instead of the built-in Compile(). FastExpressionCompiler is a drop-in, dependency-free replacement for LambdaExpression.Compile() that produces the same delegate much faster:
dotnet add package FastExpressionCompilerusing FastExpressionCompiler;
var lambda = ExpressionParser.Parse("Math.Pow(x, y) + 5", options);var func = (Func<double, double, double>)lambda.CompileFast();Benchmark
Section titled “Benchmark”| Expression | Compile() |
CompileFast() |
Speedup |
|---|---|---|---|
Math.Pow(x, y) + 5 |
28.23 µs | 2.24 µs | ~12.6x |
x switch { ... } with LINQ Select/Sum |
180.92 µs | 5.98 µs | ~30x |
The more complex the expression tree, the bigger the gap, since most of the reflection-emit overhead Compile() pays per node is avoided by CompileFast().
Benchmark source: CompileToDelegate.cs.
Dynamic / Runtime-defined types
Section titled “Dynamic / Runtime-defined types”CustomPropertyResolver lets an expression navigate types whose shape only exists at runtime - a database row, a CMS content type, a value that lives in another process.
The pattern:
- Represent every runtime-shaped value with one real, fixed .NET type (not
object, not a type generated per shape). Keep the actual field names/types in a separate schema object. (in example: Value/Instance =DynamicRecord, ValueType =DynamicRecordSchema) - In
CustomPropertyResolver, look up the requested member by name against that schema, and build a call to read it. - Attach the schema to the result with
context.IncludeTypeInfo(expression, schema), so a later.Memberfurther down the chain can retrieve it again throughcontext.InstanceTypeInfo.
// Schema (DynamicRecordSchema and DynamicRecord are example types)var personSchema = new TypeSchema(new Dictionary<string, TypeSchema> { ["Name"] = new(typeof(string)), ["Age"] = new(typeof(int)) });var rootSchema = new TypeSchema(new Dictionary<string, TypeSchema> { ["People"] = new("Person", true) });var dataSourceSchema = new DynamicRecordSchema { ["Person"] = personSchema, ["this"] = rootSchema };
// Sourcevar alice = new DynamicRecord { ["Name"] = "Alice", ["Age"] = 30 };var root = new DynamicRecord { ["People"] = new List<DynamicRecord> { alice } };
// Parsevar options = new ExpressionParserOptions{ Parameters = { (typeof(DynamicRecord), "this") }, UseFirstParameterAsThis = true, CustomPropertyResolver = x => Resolver(dataSourceSchema, x)};var expression = "People.Where(p => p.Age > 18).Select(x => x.Name).First()";var result = ExpressionParser.Invoke<string>(expression, options, root); // Alice
// ResolverExpression? Resolver(DynamicRecordSchema dataSourceSchema, IExpressionMemberResolverContext context){ if (context.Instance.Type != typeof(DynamicRecord)) return null;
// Member type var instanceSchema = context.InstanceTypeInfo as TypeSchema ?? (context.MemberFullPath == "this." + context.MemberName ? dataSourceSchema.GetValueOrDefault("this") : null); if (instanceSchema == null) return null;
if (instanceSchema.Fields == null && instanceSchema.Name != null) { instanceSchema = dataSourceSchema.GetValueOrDefault(instanceSchema.Name); if (instanceSchema == null) return null; }
// Value if (instanceSchema.Fields?.TryGetValue(context.MemberName, out var fieldTypeScheme) != true) return null;
var fieldType = fieldTypeScheme!.Type; var isKnownType = fieldType != null; if (fieldType == null) { fieldType = typeof(DynamicRecord); if (fieldTypeScheme.IsCollection) fieldType = typeof(IList<DynamicRecord>); }
var method = typeof(DynamicRecord).GetMethod(nameof(DynamicRecord.GetValue))!.MakeGenericMethod(fieldType); var result = Expression.Call(context.Instance, method, Expression.Constant(context.MemberName));
return !isKnownType ? context.IncludeTypeInfo(result, fieldTypeScheme) // Wrap expression to include a type info : result;}
// Sample value and schema typesclass DynamicRecord : Dictionary<string, object>{ public T GetValue<T>(string name) => TryGetValue(name, out var value) && value is T v ? v : default;}class DynamicRecordSchema : Dictionary<string, TypeSchema>;class TypeSchema { /* ... */ }LINQ over a dynamic collection works without any extra code, as long as the collection itself is exposed as a real, closed type - IEnumerable<DynamicRecord>. Because it’s a real type, extensions like Where or Select, Sum, Count resolve as ordinary LINQ extension methods. CustomPropertyResolver never has to intercept a method call, only plain member access. And the element parameter of a lambda passed to one of those methods automatically inherits the collection’s InstanceTypeInfo, so it’s correctly typed too.
Parameters and global members have no type info, so every “dynamic” object must by resolved by resolver.
Peopleresolves throughCustomPropertyResolverand is tagged viacontext.IncludeTypeInfo(call, PersonSchema). Inside the lambda,p“knows” it’s aPersontoo, because parser extracts that same type info from the collection and applies it top, sop.Ageis resolved by the very same resolver branch that resolvedPeople.
Type info is propagated through method chains only for collections. The receiver has to be anIEnumerable<X>, and the info flows to a result that keeps the same element type: anotherIEnumerable<X>(Where,Select,OrderBy, …) or a singleX(First,FirstOrDefault, …). That’s whyPeople.Where(...).First().Namestill knows the element is aPerson.
Full example: CustomPropertyResolverTests.cs.
Alternatives
Section titled “Alternatives”TagBites.Expressions fits between lightweight expression evaluators and full C# scripting engines: it supports real C# expression syntax through Roslyn, returns delegates or expression trees, and avoids generating a new assembly.
| TagBites.Expressions | DynamicExpresso | System.Linq.Dynamic.Core | Roslyn scripting (CSharpScript) |
|
|---|---|---|---|---|
| Language | C# expressions (Roslyn) | C#-like (own parser) | Dynamic LINQ dialect | Full C# (official) |
| Output | Delegate / Expression | Delegate / Expression | Expression tree | Compiled assembly |
| Startup / memory | Low | Low | Low | High |
| Dependency | Roslyn | None | None | Roslyn |
Comparison
Section titled “Comparison”The table below is generated by LibraryFeatureComparer.cs (run the benchmarks project with the feature-comparer argument).
Rows are ordered by how many of the three libraries support each feature, most first:
| C# syntax | TagBites.Expressions v. 1.3.0 |
DynamicExpresso v. 2.19.3 |
System.Linq.Dynamic.Core v. 1.7.3 |
|---|---|---|---|
| Arithmetic and logical operators | ✅ | ✅ | ✅ |
| Ternary | ✅ | ✅ | ✅ |
| Member access and method calls | ✅ | ✅ | ✅ |
params method call (string.Format("{0}{1}", 1, 2)) |
✅ | ✅ | ✅ |
| Lambdas and LINQ | ✅ | ✅ | ✅ |
is / as |
✅ | ✅ | ❌ |
typeof, default(T) |
✅ | ✅ | ❌ |
Null-coalescing ?? / null-conditional ?. |
✅ | ✅ | ❌ |
| Object and collection initializers | ✅ | ✅ | ❌ |
User-defined operator overloads (DateTime.Now + TimeSpan.FromDays(1)) |
✅ | ❌ | ✅ |
| User-defined implicit/explicit conversion operators | ✅ | ❌ | ✅ |
Named arguments, reordered (Substring(length: 2, startIndex: 1)) |
✅ | ❌ | ❌ |
Indexers and index-from-end (xs[^1]) |
✅ | ❌ | ❌ |
Bare default literal (target-typed) |
✅ | ❌ | ❌ |
Verbatim strings @"..." |
✅ | ❌ | ❌ |
Digit separators 1_000 |
✅ | ❌ | ❌ |
String interpolation $"{x,6:0.00}" (alignment + format) |
✅ | ❌ | ❌ |
Raw string literals """...""" |
✅ | ❌ | ❌ |
| Tuples and tuple equality | ✅ | ❌ | ❌ |
| Tuples with named elements | ✅ | ❌ | ❌ |
Anonymous objects (new { X = 1 }) |
✅ | ❌ | ❌ |
Null-forgiving x! |
✅ | ❌ | ❌ |
checked / unchecked |
✅ | ❌ | ❌ |
nameof, sizeof |
✅ | ❌ | ❌ |
| Array creation: sized and multidimensional | ✅ | ❌ | ❌ |
Target-typed new() |
✅ | ❌ | ❌ |
Generic method call with explicit type argument (xs.OfType<int>()) |
✅ | ❌ | ❌ |
Static imports (using static, unqualified Sqrt(16)) |
✅ | ❌ | ❌ |
| Switch expressions | ✅ | ❌ | ❌ |
Pattern matching: relational, and/or/not, property |
✅ | ❌ | ❌ |
List patterns (arr is [1, 2, 3]) |
✅ | ❌ | ❌ |
Tuple/recursive deconstruction patterns (x is (int a, int b)) |
✅ | ❌ | ❌ |
✅/❌ is based on parsing and evaluating each expression to the expected result, not just on whether parsing throws.
Benchmark
Section titled “Benchmark”Parsing expressions: "Math.Pow(x, y) + 5" and list.Where(x => x > limit).Select(x => Math.Pow(x, y)).Sum().
The table below is generated by Program.cs.
| TestCase | TagBites.Expressions v. 1.3.1 |
DynamicExpresso v. 2.19.3 |
System.Linq.Dynamic.Core v. 1.7.3 |
|---|---|---|---|
| Parse | 5,65 us (1,00x)5,85 KB (1,00x) |
21,61 us (3,83x)30,75 KB (5,25x) |
3009,26 us (532,8x)276,86 KB (47,31x) |
| Parse_SharedEnv | 3,81 us (1,00x)2,96 KB (1,00x) |
11,30 us (2,97x)12,33 KB (4,16x) |
61,82 us (16,24x)100,96 KB (34,10x) |
| ParseLambda | 66,04 us (1,00x)35,35 KB (1,00x) |
188,13 us (2,85x)122,75 KB (3,47x) |
2990,92 us (45,29x)206,84 KB (5,85x) |
| ParseLambda_SharedEnv | 20,06 us (1,00x)11,24 KB (1,00x) |
170,51 us (8,50x)104,19 KB (9,27x) |
32,13 us (1,60x)35,26 KB (3,14x) |
SharedEnv = shared options/interptreter/config.
SharedOptions for TagBites.Expressions usesUseMemberCache = true.
Benchmark source: ParseToExpression.cs.