7

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?

AdamBT
  • 1,936
  • 2
  • 30
  • 48
  • an important side note about the use of == versus .Equals() in LinqToSql, http://stackoverflow.com/questions/8105732/ef-4-1-linq-to-sql-what-is-better-using-equals-or – Zach Green Feb 17 '12 at 14:07

2 Answers2

11

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.

5

Your comparison is translated to SQL, and SQL behaves differently from C# and .NET Framework. It's similar to how "a" == "A" is false in C#, but may be true when it's part of a query.