Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do Linq Expressions determine equality?

I am considering using a Linq Expression as a key in a dictionary. However, I am concerned that I will get strange results, because I don't know how Equality is determined by Linq expressions.

Does a class derived from Expression compare value equality or reference equality? Or in other words,

        Expression<Func<object>> first = () => new object(); 
        Expression<Func<object>> second = ()=>new object();
        bool AreTheyEqual = first == second;
like image 402
smartcaveman Avatar asked Feb 17 '11 18:02

smartcaveman


1 Answers

Your test compares expressions. Expressions themselves offer only reference equality; your test will probably show "false". To cheek for semantic equality you would need to do a lot of work, for example - are:

x => 123

And

y => 123

Equivalent? As a crude test you can compare ToString(), but this will be exceptionally brittle.

like image 137
Marc Gravell Avatar answered Sep 28 '22 05:09

Marc Gravell