GameDevWare.Dynamic.Expressions
3.1.0
dotnet add package GameDevWare.Dynamic.Expressions --version 3.1.0
NuGet\Install-Package GameDevWare.Dynamic.Expressions -Version 3.1.0
<PackageReference Include="GameDevWare.Dynamic.Expressions" Version="3.1.0" />
<PackageVersion Include="GameDevWare.Dynamic.Expressions" Version="3.1.0" />
<PackageReference Include="GameDevWare.Dynamic.Expressions" />
paket add GameDevWare.Dynamic.Expressions --version 3.1.0
#r "nuget: GameDevWare.Dynamic.Expressions, 3.1.0"
#:package GameDevWare.Dynamic.Expressions@3.1.0
#addin nuget:?package=GameDevWare.Dynamic.Expressions&version=3.1.0
#tool nuget:?package=GameDevWare.Dynamic.Expressions&version=3.1.0
C# Eval() for Unity
This package delivers a robust C# parsing and expression execution API designed for Unity compatibility across multiple platforms. Implemented in C# with no external dependencies, it maintains broad compatibility with modern Unity versions and .NET frameworks.
Licensing
This package is available for purchase on the Unity Asset Store. A valid license is required for use in any project. See License.md for details.
Quick Start
Expression Evaluation
Evaluate simple C# expressions immediately:
using GameDevWare.Dynamic.Expressions.CSharp;
var result = CSharpExpression.Evaluate<int>("2 * (2 + 3) << 1");
// Returns 20
Expression Parsing and AOT Compilation
Parse an expression once and execute it multiple times with high performance:
using GameDevWare.Dynamic.Expressions.CSharp;
using System.Linq.Expressions;
var mathExpr = "Math.Max(x, y)";
var exprTree = CSharpExpression.ParseFunc<double, double, double>(mathExpr, arg1Name: "x", arg2Name: "y");
// Returns Expression<Func<double, double, double>>
var func = exprTree.CompileAot();
// Returns Func<double, double, double>
var result = func(10.5, 20.0); // 20.0
Verified Platform Support
- iOS (IL2CPP)
- Android (Mono/IL2CPP)
- WebGL
- Windows / macOS / Linux
- Consoles (Nintendo Switch, PS4/PS5, Xbox)
AOT Platforms (iOS, WebGL, IL2CPP):
Projects targeting AOT compilation require a link.xml file to prevent code stripping. A sample is provided in the package. Refer to Unity's documentation on IL code stripping for more context.
Core API Features
The parser implements C# 4.0+ grammar with support for:
- Operations: Arithmetic, bitwise, logical, Conditional (?:), and Null-coalescing (??).
- Invocations: Methods, delegates, and constructors.
- Access: Properties, fields, and indexers.
- Types: Casting, is/as operators,
typeof(), anddefault(). - Contexts: Checked/Unchecked blocks.
- Advanced: Null-conditional (?. and ?[]), Power operator (
**), and Lambda expressions. - Generics: Generic types and methods, with limited inference of a method's type arguments when they are not given explicitly.
- Extension methods: Extension methods declared by known types, including LINQ queries over sequences.
- Serialization: Pack/Unpack expressions into serializable structures.
Type Resolution & Security
For security, the parser restricts type access by default. Additional types must be registered:
// Register specific types
var typeResolver = new KnownTypeResolver(typeof(Mathf), typeof(Time));
CSharpExpression.Evaluate<float>("Mathf.Clamp(Time.time, 0f, 1f)", typeResolver);
// Or allow an entire assembly
var assemblyResolver = new AssemblyTypeResolver(typeof(UnityEngine.Vector3).Assembly);
A registered static class also makes its extension methods available on the types they extend. System.Linq.Enumerable is registered by default, so LINQ queries work without any registration:
var items = new[] { 1, 2, 3 };
CSharpExpression.Evaluate<int[], int>("a.Where(x => x > 1).Sum()", items, "a"); // 5
An extension method is only considered when the target's own type declares no applicable method, so a declared method always wins. A member of a delegate type is invoked in preference to an extension method of the same name.
Generic Type Argument Inference
A generic method called without explicit type arguments has them inferred from the types of its arguments, including the receiver of an extension method. The result type of a lambda argument is inferred by binding its body, so projections stay strongly typed rather than degrading to object:
var items = new[] { 1, 2, 3 };
// binds Enumerable.Select<int, string>, the expression's type is IEnumerable<string>
CSharpExpression.Evaluate<int[], IEnumerable<string>>("a.Select(x => x.ToString())", items, "a");
This is a limited form of inference, enough for Enumerable queries and ordinary extension methods, but not the full C# algorithm:
- A type parameter is fixed by the first argument mentioning it; there is no best common type across several arguments. Given
Pair<T>(T a, T b), the callPair(2.0, 1)bindsTtodouble, whilePair(1, 2.0)fails to bind. - Type parameters are inferred from parameters only. One appearing solely in the return type has to be given explicitly, as it does in C#.
- Constraints are verified after inference rather than used to drive it.
- A lambda argument contributes only once its own parameter types are known, which they are for the
Enumerableoperators.
Explicit type arguments are always honoured and skip inference entirely: a.Where<int>(x => x > 1).
On AOT runtimes an inferred call still instantiates the method at bind time, so see AOT Considerations for the registrations LINQ queries need.
AOT Compilation Support
High-performance execution on AOT platforms (iOS, WebGL, Consoles) is achieved via CompileAot():
var expr = (Expression<Func<Vector3>>)(() => new Vector3(1f, 1f, 1f));
var fn = expr.CompileAot(); // Uses AOT-safe execution if needed
AOT Considerations
- Only
Expression<Func<...>>andExpression<Action<...>>are supported. - Register required delegate types:
AotCompilation.RegisterFunc<int, string>();. - Use
AotCompilation.RegisterForFastCall<TTarget, TResult>()for maximum performance on critical paths. - Register the element type of every sequence a LINQ query runs over:
AotCompilation.RegisterLinqFunc<int>();, and useAotCompilation.RegisterLinqFunc<int, string>()when the query projects elements to another type (Select,OrderBy).
Installation
Unity Asset Store
- Open Window > Package Manager.
- Select Packages: My Assets.
- Find C# Eval() and click Download/Import.
NuGet (Standalone .NET)
Install-Package GameDevWare.Dynamic.Expressions
Roadmap & Support
We are continuously improving the package. Planned features include:
- Generic type inference
- C# 6.0+ extended syntax support
- Extension method support
Support: support@gamedevware.com
Change Log (Highlights)
3.1.0
- Feature: Added extension method invocation and LINQ queries, with type argument inference for generic methods.
- Feature: Added hexadecimal (
0x1F) and verbatim string (@"c:\temp") literals. - Breaking: C# cast disambiguation:
(x) - 1is subtraction; write(Int32)(-1)or(int)-1instead of(Int32)-1. - Breaking: C# string escapes (
\a,\v,\0,\U, 1-4 digit\x); decimal escapes like"\112"removed. - Breaking:
**is right-associative and binds tighter than*,/,%. - Fix: Integer literals widen to
uint/long/ulongper C# spec;1e5isdouble. - Fix: Many tokenizer/parser fixes (keyword-prefixed identifiers,
1e5+3, mismatched brackets, curried lambdas, token positions). - Fix: Deeply nested expressions throw
ExpressionParserExceptioninstead of crashing withStackOverflowException.
3.0.2
- Feature: Added out/ref parameter write-back for Invoke node and AOT expression executor.
- Fix: Fixed multi-dimensional array packing/unpacking.
3.0.1
- Fix: Correctly format new expression types (Member/List Init) from syntax trees.
- Change: Internal renaming of
AssignmenttoAssignmentBinding(backward compatible).
3.0.0
- Breaking: Distributed as a Unity Package instead of a legacy
.dll. - Feature: Added support for Object and Collection Initializers.
- Chore: Increased C# language support and raised minimum .NET version to 4.6+.
2.3.0
- Feature: Added
globalparameter for context-aware expressions. - Fix: Standardized
arg4Namenaming across methods.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net5.0 was computed. net5.0-windows was computed. net6.0 is compatible. 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 is compatible. 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 | netcoreapp1.0 was computed. netcoreapp1.1 was computed. netcoreapp2.0 was computed. netcoreapp2.1 was computed. netcoreapp2.2 was computed. netcoreapp3.0 was computed. netcoreapp3.1 is compatible. |
| .NET Standard | netstandard1.6 is compatible. netstandard2.0 was computed. netstandard2.1 is compatible. |
| .NET Framework | net45 is compatible. net451 was computed. net452 was computed. net46 was computed. net461 is compatible. net462 was computed. net463 was computed. net47 was computed. net471 was computed. net472 was computed. net48 is compatible. net481 was computed. |
| MonoAndroid | monoandroid was computed. |
| MonoMac | monomac was computed. |
| MonoTouch | monotouch was computed. |
| Tizen | tizen30 was computed. 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. |
-
.NETCoreApp 3.1
- No dependencies.
-
.NETFramework 4.5
- No dependencies.
-
.NETFramework 4.6.1
- No dependencies.
-
.NETFramework 4.8
- No dependencies.
-
.NETStandard 1.6
- NETStandard.Library (>= 1.6.1)
-
.NETStandard 2.1
- No dependencies.
-
net10.0
- No dependencies.
-
net6.0
- No dependencies.
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 3.1.0 | 48 | 11/20/2026 |
| 3.0.1 | 422 | 2/7/2026 |
| 2.3.0 | 1,644 | 3/26/2023 |
| 2.2.9 | 722 | 10/10/2022 |
| 2.2.8 | 799 | 2/17/2022 |
| 2.2.7 | 2,183 | 11/29/2020 |
| 2.2.6 | 1,475 | 9/15/2019 |
| 2.2.5 | 1,217 | 4/20/2019 |
| 2.2.4 | 1,284 | 9/3/2018 |
| 2.2.2 | 2,238 | 5/16/2018 |
| 2.2.1 | 2,268 | 12/19/2017 |
| 2.2.0 | 2,315 | 11/30/2017 |
| 2.1.4 | 1,918 | 10/22/2017 |
# 3.1.0
feature: Added extension method invocation and LINQ queries in expressions, with type argument inference for generic methods.
feature: Added hexadecimal integer literals (`0x1F`, `0xFFu`, `0x10L`, `0x10ul`).
feature: Added verbatim string literals (`@"c:\temp"`, `""` as escaped quote).
BREAKING CHANGE: Applied C# cast disambiguation rule. `(x) - 1` and `(x) + 1` are now binary operations, not casts. `(T)y` is a cast only if `T` is a keyword type (`int`, `int?`, `T[]`) or the token after `)` is `~`, `!`, `(`, identifier, literal, number or `new`. Write `(Int32)(-1)` or `(int)-1` instead of `(Int32)-1`.
BREAKING CHANGE: String escapes follow C#: added `\a`, `\v`, `\0`, `\U00000000`, `\x` takes 1-4 hex digits (`"\x038"` is `"8"`), removed non-C# decimal escapes like `"\112"`.
BREAKING CHANGE: `**` operator is right-associative and binds tighter than `*`, `/`, `%`: `2 ** 3 ** 2` is `512`, `2 * 3 ** 2` is `18`.
fix: Integer literals take the first fitting type per C# spec: `int`, `uint`, `long`, `ulong` (with `u` suffix: `uint`, `ulong`; with `l` suffix: `long`, `ulong`). Values beyond `ulong` report "Integral constant is too large".
fix: Exponent-only number literals are `double` (`1e5`, `2E3`). Exponent is allowed in `decimal` literals (`1e5m`).
fix: Exponent accepts a sign only right after `e`, so `1e5+3` is an addition.
fix: Keyword followed by a digit or `_` is part of an identifier (`is_valid`, `new_value`, `as_x`, `is2`).
fix: `?.` followed by a digit is a conditional with a short number (`x?.5:1`).
fix: Closing bracket must match the opening one, `(1 + 2]` and `a[0)` are errors now.
fix: Lambda is right-associative, curried lambdas `x => y => x` are supported.
fix: Expression nesting depth is limited to 256, deeply nested expressions throw `ExpressionParserException` instead of crashing with `StackOverflowException`. Errors deep inside nested expressions no longer exhaust the stack.
fix: Char literal must contain exactly one character.
fix: Correct line/column positions for identifiers, tokenizer errors and tokens after multiline string literals.
fix: `f(a < b, c > d)` is parsed as comparisons, not generic arguments.
fix: Cast to array type `(int[])x`, including jagged arrays.
# 3.0.2
feature: Added out/ref parameter write-back for Invoke node and AOT expression executor.
fix: Fixed multi-dimensional array packing/unpacking.
chore: Added better documentation.
# 3.0.1
fix: Added formatting of new expression types (Member Init/List Init) from the syntax tree.
fix: changed the name of `Assignment` binding name to `AssignmentBinding`, the code is backwards compatible with the old name.
# 3.0.0
BREAKING CHANGE: Changed the distribution form to Unity Package instead of a library.
feature: Added parser support for object initializers and collections initializers.
fix: fix for Mono failture to return underlying type code for Enum types
fix: fixed detection of IsByRefLike types in reflection on Mono.
chore: Increased C# language support to version 7.3 and formatted the code.
BREAKING CHANGE: Raised the minimum .NET Framework version to 4.6.
chore: Added new compilation targets to support modern .NET versions.
# 2.3.0
fix: fixed netcore related error with enumerable.empty<T>
feature: added optional `global` parameter to all CSharpExpression methods to allow specify global object for expression.
test: removed flaky test with double.tostring() comparison
fix: fixed typo in `arg4Name` in `CSharpExpression.ParseFunc{4}` and `CSharpExpression.ParseAction{4}`
# 2.2.9
fix: fixed error with instantiated generic method on types (which is impossible in normal conditions, but fine for Unity AOT runtime).
# 2.2.8
- made AotCompilation.IsAotRuntime is mutable, this will allow to signal for AOT runtime and suppress further checks.
# 2.2.7
- added public CSharpExpression.Format method for SyntaxTreeNode
# 2.2.6
- changed order or SyntaxTreeNode fields and added "original C# expression" field to parsed AST.
- refactored C# expression rendering to support null-propagation expressions, type aliases (int, byte, object ...),
- renamed "Render" methods to "FormatAsCSharp". Now it is "formatting"
- moved c# "formatting" methods to CSharpExpression class
- mark old "Parse" functions as errors
- mark old "Render" methods as obsolete
- renamed CSharpExpressionFormatter to CSharpExpressionFormatter
- fixed indexer experssion rendering
- refactored NameUtils to properly render C# type names
# 2.2.5
renamed ParseTreeNode.Lexeme to .Token
renamed few member of TokenType for better clarity
added documentation file in Unity project assets
changed 'propertyOrFieldName' attribute to 'name' in SyntaxTreeNode
renamed PropertyOfFieldBinder to MemberBinder
changed 'PropertyOrField' expression type to 'MemberResolve' in SyntaxTreeNode
added backward compatibility checks in all related classes
# 2.2.4
added protection against wrong expressions like 'a b' which later bound as 'b'
fixed some tokenization errors:
- 'issa'scanned as 'is'[Operator] and 'sa'[Identifier], now as 'issa'
- '.09' scanned as '.'[Operator] and '09'[Number], now as '0.09'
- '0.1x' scanned as '0.1'[Number] and 'x'[Identifier], now cause error
added method call support for numbers (example 1.ToString())
added short number notation (examples '.9' for '0.9')
added '@' prefix for identifiers (example '@is') https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/verbatim
done small Tokenizer optimization (reduced string allocation during scanning)
# 2.2.3
added ExpressionPacker type. This type allows packing/unpacking expressions into primitive structures (Dictionaries, Arrays...). These structures could be serialized and wired by network or stored for future use.
added better error message for some binding cases
denying call to 'Type.InvokeMember' if 'Type' is not within 'known types'.
# 2.2.2
* fixed conditional operator (a ? b : c) parsing with method call in place of 'b'
# 2.2.1
* fixed IL2CPP compilation error due _Attribute interface complilation failure
* added few interfaces to AOT.cs file for better AOT coverage
# 2.2.0
Features
* added support for void expressions (Action<> delegates)
* added support of '.NET Standart 1.3' and '.NET Core 2.0' platforms