Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using the equals keyword in linq [duplicate]

Possible Duplicate:
Lambda Expression: == vs. .Equals()

Hi,

I use a lot the keyword Equals to compare variables and other stuff.

but

wines = wines.Where(d => d.Region.Equals(paramRegion)).ToList();

return an error at runtime when in the data Region is NULL

I had to use the code

wines = wines.Where(d => d.Region == paramRegion).ToList();

to get rid of the error.

Any ideas why this raises an error?

Thanks.

like image 462
Filip Avatar asked Jan 29 '11 14:01

Filip


2 Answers

You cannot call instance methods with null object reference. You should check that the Region is not null before calling its instance methods.

wines = wines.Where(d => d.Region != null && d.Region.Equals(paramRegion)).ToList();

The d.Region == paramRegion is (most likely) expanded to object.Equals(d.Region, paramRegion) and that static method does check whether the parameters are null or not before calling the Equals() method.

You can also write the condition in different order if you know that the paramRegion cannot be null.

Debug.Assert(paramRegion != null);
wines = wines.Where(d => paramRegion.Equals(d.Region)).ToList();
like image 109
mgronber Avatar answered Oct 16 '22 06:10

mgronber


Basically if

d.Region == null

then any method call, here it's Equals(...) on that will raise an exception since it's not initialized.

like image 28
laika Avatar answered Oct 16 '22 05:10

laika