In addition to Jon’s answer which explains the C# side of things, here’s what VB does:
In VB with Option Strict On
, a comparison via =
always tests for value equality and never for reference equality. In fact, your code doesn’t even compile once you switch Option Strict On
because System.Object
doesn’t define an Operator=
. You should always have this option on, it catches bugs more effectively than a venus flytrap (although in your particular case this lax behaviour actually does the right thing).1
In fact, with Option Strict On
, VB behaves even stricter than C#: In C#, a == b
either triggers a call to SomeType.operator==(a, b)
or, if this doesn’t exist, invokes reference equality comparison (which is equivalent to calling object.ReferenceEquals(a, b)
).
In VB on the other hand, the comparison a = b
always invokes the equality operator.2 If you want to use reference equality comparison, you have to use a Is b
(which is, once again, the same as Object.ReferenceEquals(a, b)
).
1) Here’s a good indication why using Option Strict Off
is a bad idea: I’ve used VB.NET for almost a decade, from before .NET’s official release until a few years ago, and I’ve absolutely no idea what a = b
does with Option Strict Off
. It does some kind of equality comparison, but what exactly happens and why, no idea. It’s more complex than C#’s dynamic
feature, though (because that relies on a well-documented API). Here’s what the MSDN says:
Because Option Strict On
provides strong typing, prevents unintended type conversions with data loss, disallows late binding, and improves performance, its use is strongly recommended.
2) Jon has mentioned one exception, strings, where equality comparison does some more things for reasons of backwards compatibility.
a.Equals(b)
? – Inculcatea
you get boxing and create a box containingtrue
. When you assign tob
you get another box also containingtrue
. When you comparea
andb
, because both are of compile-time typeobject
, you call the overloadoperator ==(object, object)
defined by the C# Language Specification. This overload checks to see if the references go to the same object. Since you have two boxes, the result isfalse
, and the statement "under" yourif
will not run. To understand this better, try to change the assignment ofb
to this:object b = a;
Now you have just one box. – Bacolod