Sunday 23 February 2014

Identity vs Equality

Most of my time in software development has been spent with .NET and C#. And sometimes, owing to that, i figure that i miss out on knowing some of the interesting features present in other programming languages and "run time" environments. I have done a bit of JavaScript development for some web applications as well but most of it was quite basic and therefore when I realize the powerful implementations in JavaScript language I ask myself "why do people take JavaScript language so lightly". One such example is "Identity Operator" which i came across on this thread.

In C# (and .NET in general), we work with strongly typed code and therefore the comparison of "type" is implicitly taken care of at the compile time. But this situation changes when we work with "dynamic" types in .NET. "Script" kind of languages seem to have more in-built implementation to deal with situation, most probably because such kind of code is expected by their run time.

Consider the following JavaScript code:


The run time performs implicit conversion to ensure that comparison can be worked out between two variables when executing "Equality" operator. When executing "Identity" operator (===), it compares the types and if they are not same it returns false. 

Consider the following SQL Server table (with the data):

If you run a query (that uses comparison operator) like following:

SELECT [Id],[FirstName],[MiddleName],[LastName]
FROM [Test].[dbo].[Customer]
WHERE [MiddleName] = 8989

The query runs just fine even though the values have different "type" associated.

Let us try that in .NET. I added the below code in a standard ASP.NET MVC project's controller:


The above mentioned code compiles just fine but produces a run time error (as expected). It will not work even if you try to make "y" as dynamic as well.


Lesson : If you spend more time with just one language, you take interesting things for granted.