Why C# fails to compare two object types with each other but VB doesn’t?

In C#, the == operator (when applied to reference type expressions) performs a reference equality check unless it’s overloaded. You’re comparing two references which are the result of boxing conversions, so those are distinct references.

EDIT: With types which overload the ==, you can get different behaviour – but that’s based on the compile-time type of the expressions. For example, string provides ==(string, string):

string x = new string("foo".ToCharArray());
string y = new string("foo".ToCharArray());
Console.WriteLine(x == y); // True
Console.WriteLine((object) x == (object) y); // False

Here the first comparison is using the overloaded operator, but the second is using the “default” reference comparison.

In VB, the = operator does a whole lot more work – it’s not even just equivalent to using object.Equals(x, y), as things like Option Compare can affect how text is compared.

Fundamentally the operators don’t work the same way and aren’t intended to work the same way.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)