-
Notifications
You must be signed in to change notification settings - Fork 26
Home
Given an expression tree:
Expression<Func<Person, bool>> expr = p =>
p.DOB.DayOfWeek == DayOfWeek.Tuesday;.NET provides a mechanism for representing an expression tree as a string, using the built-in .ToString:
Console.WriteLine(expr);
/*
p => (Convert(p.DOB.DayOfWeek) == 2)
*/However, the resulting string is lacking a number of features: e.g. conversions (Convert(...) vs (int)...), type names use the Type.Name property (List`1 vs List<string>), closed-over variables (): (value(sampleCode.Program+<>c__DisplayClass0_0).i vs i).
There is also the DebugView property, available only while debugging, which uses a special syntax to represent expression trees:
.Lambda #Lambda1<System.Func`2[sampleCode.Person,System.Boolean]>(sampleCode.Person $p) {
(System.Int32)($p.DOB).DayOfWeek == 2
}
but the additional information is not always necessary.
The string rendering library is implemented as a set of .ToString set of extension methods on the various types used in expression trees. You pass in the name of the formatter to use when rendering the expression tree:
Console.WriteLine(expr.ToString("C#"));
/*
(Person p) => (int)p.DOB.DayOfWeek == 2
*/
Console.WriteLine(expr.ToString("Visual Basic"));
/*
Function(p As Person) CInt(p.DOB.DayOfWeek) = 2
*/The longer and more invloved an