tags:

views:

51

answers:

1

There is no IdentityEqual item in ExpressionType enumeration. How can I construct expreesion tree with VB.NET Is operator?

+1  A: 

Have you tried using Expression.Equal, specifying the implementation to use?

In C#:

MethodInfo referenceEquality = typeof(object).GetMethod("ReferenceEquals",
    BindingFlags.Static | BindingFlags.Public);
Expression equality = Expression.Equal(lhs, rhs, true, referenceEquality);

Here's a complete example (again, C# - but you should be able to translate it easily):

using System;
using System.Reflection;
using System.Linq.Expressions;

class Test
{
    static void Main()
    {
        var lhs = Expression.Parameter(typeof(string), "lhs");
        var rhs = Expression.Parameter(typeof(string), "rhs");        
        MethodInfo referenceEquality = typeof(object).GetMethod
            ("ReferenceEquals", BindingFlags.Static | BindingFlags.Public);
        var equality = Expression.Equal(lhs, rhs, true, referenceEquality);
        var lambda = Expression.Lambda<Func<string, string, bool>>
            (equality, new[] { lhs, rhs });

        var compiled = lambda.Compile();

        string x = "hello";
        string y = x;
        string z = new string(x.ToCharArray());
        Console.WriteLine(compiled(x, y)); // True
        Console.WriteLine(compiled(x, z)); // False
    }
}
Jon Skeet
Thank you, Jon!It's a great idea! But I cann't construct trees manualy. It's a compiler work.Dim exp as Expression(Of Func(Of String, String, Bool)) = Function(x,y) x Is yIn the tree ExpressionType of BinaryExpression will be equlas ExpressionType.Equal.
Alexey Shirshov
I don't understand what you mean - why can't you construct the trees manually? Please give more context about what you're trying to achieve. (Note that in my example the expression type would be Equal as well... that doesn't mean there's anything wrong)
Jon Skeet
I convert expression trees to codedom trees. Expression trees created be compiler. I cannot construct every expression tree by hand, it's too complex.[code]Dim exp as Expression(Of Func(Of String, String, Bool)) = Function(x,y) x Is y[/code]exp - is expression tree. It contains BinaryExpression node which has ExpressionType property equlas to ExpressionType.Equal although I use Is operator (not =)
Alexey Shirshov
Just because the ExpressionType property is Equal doesn't mean it's wrong though... that's my point. You need to check what the method implementing the equality check is - my guess is that it'll be `object.ReferenceEquals`, which means "Is".
Jon Skeet
It's a good idea. I will check it. Sorry, cant rate.
Alexey Shirshov
Unfortunately, the method is null.
Alexey Shirshov