TagBites.Expressions
1.2.1
Prefix Reserved
dotnet add package TagBites.Expressions --version 1.2.1
NuGet\Install-Package TagBites.Expressions -Version 1.2.1
<PackageReference Include="TagBites.Expressions" Version="1.2.1" />
<PackageVersion Include="TagBites.Expressions" Version="1.2.1" />
<PackageReference Include="TagBites.Expressions" />
paket add TagBites.Expressions --version 1.2.1
#r "nuget: TagBites.Expressions, 1.2.1"
#:package TagBites.Expressions@1.2.1
#addin nuget:?package=TagBites.Expressions&version=1.2.1
#tool nuget:?package=TagBites.Expressions&version=1.2.1
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); // 3
Because 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
dotnet add package TagBites.Expressions
Targets netstandard2.0. Only dependency is Microsoft.CodeAnalysis.CSharp.
Usage
Evaluate once:
ExpressionParser.Invoke("5 / 2.5"); // 2d
ExpressionParser.Invoke<int>("new [] { 1, 2, 3 }.Sum()"); // 6
ExpressionParser.Invoke<int>("(a + b) / 2", ("a", 2), ("b", 4)); // 3
Compile 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); // 1029
func(2, 2); // 9
Bind 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 }); // 3
Expose 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); // 5
String interpolation, including alignment and format specifiers (formatting follows the current culture):
ExpressionParser.Invoke(@"$""sum = {1 + 2}"""); // sum = 3
ExpressionParser.Invoke(@"$""{5,-4}|"""); // "5 |" (left aligned)
ExpressionParser.Invoke(@"$""{5,6:000}"""); // " 005" (alignment + format)
ExpressionParser.Invoke(@"$""{255:X}"""); // FF
ExpressionParser.Invoke(@"$""{new DateTime(2021, 8, 14):yyyy-MM-dd}"""); // 2021-08-14
ExpressionParser.Invoke(@"$""{(1 < 2 ? ""yes"" : ""no"")}"""); // yes
Anonymous 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); // 18
Get 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
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?
- 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
- Operators: arithmetic, bitwise, shifts, comparison,
&& || !,?:,??,?./?[],is/as,x!. - Literals: all numeric types,
char,string, verbatim and interpolated strings, hex, digit separators. - Members and calls: properties, fields, indexers (including index-from-end
x[^1]), generic and extension methods,params. new: constructors, object and collection initializers, arrays (jagged, multidimensional and sized), target-typednew().- Anonymous objects (
new { X = 1, Y = 2 }- see Usage above). - Lambdas and LINQ (
Select,Where,GroupBy, ...), including nested and multi-argument lambdas. - Tuples, including element-wise equality.
typeof,default(T),nameof,sizeof,checked,unchecked.- Pattern matching in
isandswitch: type, constant, relational,and/or/not, property, positional andvarpatterns,whenguards.
Statements (like if), async/await, and declarations (methods, types) are out of scope - this is an expression parser.
Not currently supported:
- The range operator (
1..2,arr[1..^1]). - Target-typed
new()as a method call argument (obj.Method(new())) - use an explicit type there for now.
Configuration
ExpressionParserOptions:
| Option | Purpose |
|---|---|
AllowReflection |
Allow reflection APIs. (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. |
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>. |
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).
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. |
Advanced usage
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 FastExpressionCompiler
using FastExpressionCompiler;
var lambda = ExpressionParser.Parse("Math.Pow(x, y) + 5", options);
var func = (Func<double, double, double>)lambda.CompileFast();
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
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 };
// Source
var alice = new DynamicRecord { ["Name"] = "Alice", ["Age"] = 30 };
var root = new DynamicRecord { ["People"] = new List<DynamicRecord> { alice } };
// Parse
var 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
// Resolver
Expression? 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 types
class 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
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
Because TagBites parses with Roslyn, it accepts modern C# syntax that neither DynamicExpresso's nor System.Linq.Dynamic.Core's own parsers do.
Verified against DynamicExpresso 2.19.3 and System.Linq.Dynamic.Core 1.7.3 (see LibraryFeatureComparer.cs):
| C# syntax | TagBites | DynamicExpresso | System.Linq.Dynamic.Core |
|---|---|---|---|
String interpolation $"{x,6:0.00}" (alignment + format) |
✓ | ✗ | ✗ |
| Switch expressions | ✓ | ✗ | ✗ |
Pattern matching: relational, and/or/not, property |
✓ | ✗ | ✗ |
Tuple/recursive deconstruction patterns (x is (int a, int b)) |
✓ | ✗ | ✗ |
List patterns (arr is [1, 2, 3]) |
✓ | ✗ | ✗ |
| Tuples and tuple equality | ✓ | ✗ | ✗ |
| Array creation: sized and multidimensional | ✓ | ✗ | ✗ |
Target-typed new() |
✓ | ✗ | ✗ |
Anonymous objects (new { X = 1 }) |
✓ | ✗ | ✗ |
checked / unchecked |
✓ | ✗ | ✗ |
nameof, sizeof |
✓ | ✗ | ✗ |
Null-forgiving x! |
✓ | ✗ | ✗ |
Verbatim strings @"..." |
✓ | ✗ | ✗ |
Digit separators 1_000 |
✓ | ✗ | ✗ |
Generic method call with explicit type argument (xs.OfType<int>()) |
✓ | ✗ | ✗ |
is / as |
✓ | ✓ | ✗ |
typeof, default(T) |
✓ | ✓ | ✗ |
| Object and collection initializers | ✓ | ✓ | ✗ |
Null-coalescing ?? / null-conditional ?. |
✓ | ✓ | ✗ |
| Arithmetic and logical operators | ✓ | ✓ | ✓ |
| Member access and method calls | ✓ | ✓ | ✓ |
| Lambdas and LINQ | ✓ | ✓ | ✓ |
| Ternary | ✓ | ✓ | ✓ |
Benchmark
Parsing "Math.Pow(x, y) + 5" into a LINQ expression. TagBites (v. 1.2.0) vs DynamicExpresso (v. 2.19.3) vs System.Linq.Dynamic.Core (v. 1.7.3).
| Method | Mean | Error | StdDev | Allocated |
|---|---|---|---|---|
| TagBites_Parse | 5.710 us | 0.0331 us | 0.0692 us | 6.87 KB |
| TagBites_Parse_SharedOptions | 6.979 us | 0.0318 us | 0.0691 us | 6.52 KB |
| DynamicExpresso_Parse | 21.113 us | 0.1497 us | 0.3286 us | 30.75 KB |
| DynamicExpresso_Parse_SharedInterpreter | 10.866 us | 0.0868 us | 0.1812 us | 12.32 KB |
| DynamicLinqCore_Parse | 2,805.649 us | 28.0976 us | 61.0818 us | 271.85 KB |
| DynamicLinqCore_Parse_SharedConfig | 62.598 us | 0.4017 us | 0.8734 us | 101.01 KB |
Benchmark source: ParseToExpression.cs.
Links
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net5.0 was computed. net5.0-windows was computed. net6.0 was computed. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 was computed. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. net8.0 was computed. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
| .NET Core | netcoreapp2.0 was computed. netcoreapp2.1 was computed. netcoreapp2.2 was computed. netcoreapp3.0 was computed. netcoreapp3.1 was computed. |
| .NET Standard | netstandard2.0 is compatible. netstandard2.1 was computed. |
| .NET Framework | net461 was computed. net462 was computed. net463 was computed. net47 was computed. net471 was computed. net472 was computed. net48 was computed. net481 was computed. |
| MonoAndroid | monoandroid was computed. |
| MonoMac | monomac was computed. |
| MonoTouch | monotouch was computed. |
| Tizen | tizen40 was computed. tizen60 was computed. |
| Xamarin.iOS | xamarinios was computed. |
| Xamarin.Mac | xamarinmac was computed. |
| Xamarin.TVOS | xamarintvos was computed. |
| Xamarin.WatchOS | xamarinwatchos was computed. |
-
.NETStandard 2.0
- Microsoft.CodeAnalysis.CSharp (>= 4.2.0)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.