I have two objects in C# and don’t know if it’s Boolean or any other type.
However when I try to compare those C# fails to give the right answer.
I have tried the same code with VB.NET and that did it !
Can anyone tell me how to fix this if there is a solution ?
C#:
object a = true;
object b = true;
object c = false;
if (a == b) c = true;
MessageBox.Show(c.ToString()); //Outputs False !!
VB.NET:
Dim a As Object = True
Dim b As Object = True
Dim c As Object = False
If (a = b) Then c = True
MessageBox.Show(c.ToString()) '// Outputs True
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,stringprovides==(string, string):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 usingobject.Equals(x, y), as things likeOption Comparecan affect how text is compared.Fundamentally the operators don’t work the same way and aren’t intended to work the same way.