tags:

views:

326

answers:

6

This is a purely academic question, but what's the difference between using == and .Equals within a lambda expression and which one is preferred?

Code examples:

int categoryId = -1;
listOfCategories.FindAll(o => o.CategoryId == categoryId);

or

int categoryId = -1; 
listOfCategories.FindAll(o => o.CategoryId.Equals(categoryId));
+2  A: 

They can be overloaded separately, so they could provide different answers. See http://msdn.microsoft.com/en-us/library/ms173147(VS.80).aspx which discusses how to overload each. Typically they will be the same, but there's no guarantee of that. So it depends on what type the lambda object is.

Scott Stafford
+6  A: 
Joel Coehoorn
Actually, that's more the distinction is Java, where operator== cannot be overloaded to show value equality.
James Curran
Hm, what about the `string` type? It's a reference type, yet `==` looks for value equality, not reference equality.
Lucero
System.String is a RTINO (reference type in name only). It is implemented as a reference type for optimization reasons. It is designed to be treated in every way by the consumer like a value type.
Michael Meadows
@Lucero: Any reference type may overload `==`, but absent an overload, Joel's answer is correct; the default behaviour of `==` for a reference type is reference-equality.
Aaronaught
@Michael... um.. That would make it a RTIIO (reference type in implementation only)
James Curran
@James you're right, my bad.
Michael Meadows
A: 

It depends on what defined for the object. If there's no operator== defined for the class, it will use the one from the Object class, which checks Object.ReferenceEquals before eventually calling Equals().

This shows an important distinction: if you say A.Equals(B) then A must be nun-null. if you say A == B, A may be null.

James Curran
A: 

The Lambda is irrelevant here...

For value objects == and equals are the same For reference object == will be true if the objects are the same object (points to the same instance) while it is expected that equals compare the contents of the objects. This link explains it in another way.

Arve
+2  A: 

This is a duplicate of

http://stackoverflow.com/questions/814878/c-difference-between-and-equals

For some additional thoughts on different kinds of equality and how none of them do what you really want, see

http://blogs.msdn.com/ericlippert/archive/2009/04/09/double-your-dispatch-double-your-fun.aspx

Eric Lippert
I would refer you to Lucero's comment in the question as to why that question is not an exact duplicate.
Robert W