Expression tree differences between C# and VB.Net

c# expression-trees


I have a library working on expression trees. The library need to work with both C# and VB.Net

Noticed some differences between the languages on how the expression trees are constructed

  • String comparison
    () => "a" == "b" becomes Expression.Equals("a", "b")
    Function() "a" = "b" becomes Expression.Equals(Expression.Call(CompareString, "a", "b"), 0)
    (I understand why VB.Net uses CompareString here)

  • String concatenation
    () => "a" + "b" becomes Expression.Add("a", "b", String.Concat)
    Function() "a" & "b" becomes Expression.Call(String.Concat, "a", "b")

  • Optimization?
    () => !(1 == 2) becomes Expression.Not(Expression.Equals(1, 2))
    Function() Not (1 = 2) becomes Expression.NotEqual(1, 2)

My library handle all these differences but are there more differences I need to look out for?

Edit Some explanation of what my code does.

The system I work with has a filter for documents that you specify like this:

var filter = document.Filter;

To make it easier to use the filter my code allows you to specify the filter as a Expression<Func<bool>> lambda.

Expression<Func<bool>> filter = () => (123.AsStringColumn() == "abc") && (...);

My code then iterates the expression tree and calls the document filter methods as specified above. The filter does not have support for everything you can put into a lambda. Method calls is the most obvious one.

Since VB.Net generates method calls in some cases where C# does not I need to intercept these and handle them differently.

5/2/2013 11:28:41 AM

Popular Answer

The / division operator works differently in C# and VB. In C# it adapts to the data types used, while VB always converts the operands to floating point values:

() => 1 / 2 becomes Expression.Divide(1, 2)
Function() 1 / 2 becomes Expression.Divide(Expression.Convert(1, Double), Expression.Convert(2, Double))

In VB you would need to use the \ operator for integer division and / for floating point division to get the same as the / operator in C#.

5/5/2013 8:37:49 AM

Related Questions

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow