Provides a ToString extension method which returns a string representation of an expression tree (an object inheriting from System.Linq.Expressions.Expression).
Expression<Func<bool>> expr = () => true;
Console.WriteLine(expr.ToString("C#"));
// prints: () => true
Console.WriteLine(expr.ToString("Visual Basic"));
// prints: Function() True
Console.WriteLine(expr.ToString("Factory methods"));
// prints:
/*
// using static System.Linq.Expressions.Expression
Lambda(
Constant(true)
)
*/
Console.WriteLine(expr.ToString("Object notation"));
// prints:
/*
new Expression<Func<bool>> {
NodeType = ExpressionType.Lambda,
Type = typeof(Func<bool>),
Body = new ConstantExpression {
Type = typeof(bool),
Value = true
},
ReturnType = typeof(bool)
}
*/
Console.WriteLine(expr.ToString("Object notation", "Visual Basic"));
// prints:
/*
New Expression(Of Func(Of Boolean)) With {
.NodeType = ExpressionType.Lambda,
.Type = GetType(Func(Of Boolean)),
.Body = New ConstantExpression With {
.Type = GetType(Boolean),
.Value = True
},
.ReturnType = GetType(Boolean)
}
*/
Console.WriteLine(expr.ToString("Textual tree"));
// prints:
/*
Lambda (Func<bool>)
Body - Constant (bool) = True
*/Features:
-
Multiple formatters (with more planned):
- Pseudo-code in C# or VB.NET
- Factory method calls which generate this expression
- Object notation, using object initializer and collection initializer syntax to describe objects
- Textual tree, focusing on the properties related to the structure of the tree
-
Extension methods are rendered as instance methods
Expression<Func<int, int>> expr = x => Enumerable.Range(1, x).Select(y => x * y).Count(); Console.WriteLine(expr.ToString("C#")); // prints: (int x) => Enumerable.Range(1, x).Select((int y) => x * y).Count()
-
Closed-over variables are rendered as simple identifiers (instead of member access on the hidden compiler-generated class)
var i = 7; var j = 8; Expression<Func<int>> expr = () => i + j; Console.WriteLine(expr.ToString("C#")); // prints: () => i + j
-
Type names are rendered using language syntax and keywords, instead of the Type.Name property; e.g.
List<string>orList(Of Date)instead ofList`1 -
Calls to
String.ConcatandString.Formatare mapped to the+operator and string interpolation (where possible):var name = "World"; Expression<Func<string>> expr = () => string.Format("Hello, {0}!", name); Console.WriteLine(expr.ToString("C#")); // prints: () => $"Hello, {name}!"
-
Supports the full range of types in
System.Linq.Expressions, including .NET 4 expression types, andDynamicExpression- Expression (and derived types)
- ElementInit
- MemberBinding (and derived types)
- SwitchCase
- CatchBlock
- LabelTarget
For more information, see the wiki.
- Star the project
- File an issue