Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq to SQL .Equals returns true when comparing int to string --> Id.Equals("5") returns true

Tags:

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?

like image 605
AdamBT Avatar asked Feb 17 '12 13:02

AdamBT


1 Answers

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.

like image 152
NothingsImpossible Avatar answered Jan 15 '23 02:01

NothingsImpossible