Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
364 views
in Technique[技术] by (71.8m points)

.net - Why C# fails to compare two object types with each other but VB doesn't?

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...