We have a new developer that is just now learning LinqToSql. While going over his code, we noticed that he was using .Equals
instead of ==
for a value comparison. On top of that, he is comparing an int
with a string
. What completely baffled us, was that it worked!
After doing some testing it appears to only work with LinqToSql. Linq to objects returns false
and just doing int.Equals(“string”)
returns false
.
Below is a simple test using two sql tables:
Customer
Id(PK)(int)
Name(varchar)
CompanyId(FK)(int)
Company
Id(PK)(int)
Name(varchar)
Console.WriteLine("{0}.Equals(\"{1}\") returns {2}", 3, "3", 3.Equals("3"));
using (WrDataClassesDataContext wrDataContext = new WrDataClassesDataContext())
{
var customers1 = from c in wrDataContext.Customers
where c.CompanyId.Equals("3")
select c;
Console.WriteLine("int .Equals String Results: ");
foreach (Customer customer in customers1)
{
Console.WriteLine(customer.Name);
}
var customers3 = from c in wrDataContext.Customers
where c.CompanyId == 3
select c;
Console.WriteLine("int == int Results: ");
foreach (Customer customer in customers3)
{
Console.WriteLine(customer.Name);
}
}
RESULTS:
3.Equals("3") returns False
int .Equals String Results:
Mike
Joe
Candy
int == int Results:
Mike
Joe
Candy
Press any key to continue . . .
Any explanation?
LINQ to SQL generates SQL code from your LINQ query. In SQL, a comparison of an int
to a string
is perfectly valid. What happens is that by using .Equals
, you bypass the type checking the ==
operator does at compile-time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With