question

Krzysztofelechowski-8949 avatar image
0 Votes"
Krzysztofelechowski-8949 asked Krzysztofelechowski-8949 commented

ValueType and operator!=

I have the following result:
((System.ValueType) 0) != (System.ValueType) 0 && ((System.ValueType) 0) .Equals (0)
The former is a bit unexpected. What should I make of it?

dotnet-csharp
· 4
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Can you provide a small code sample to how the code is used?

0 Votes 0 ·

It is not used because it does not work:
Debug .Assert (new Enum [] { ConsoleColor .Black } [0] == (Enum) ConsoleColor .Black);

0 Votes 0 ·
Paul-5034 avatar image Paul-5034 Krzysztofelechowski-8949 ·

If you hover over the "==" of this expression in Visual Studio it might help you see what's going on:

Debug.Assert(ConsoleColor.Black == ConsoleColor.Black);


You should see this in the popup:

bool ConsoleColor.operator ==(ConsoleColor left, ConsoleColor right)

So it's using the implementation of the equality operator that's automatically available to enums.

If you hover over the double equals in your example above you should see:

bool object.operator ==(object left, object right)

This is because Enum hasn't defined an equality operator, and because it's a class it's falling back to object's implementation.

Since you've boxed the ConsoleColor on both sides of the expression inside an Enum the implementation of object's equality operator does it's default reference equality check against the two boxes and returns false.

0 Votes 0 ·
Show more comments

1 Answer

Viorel-1 avatar image
0 Votes"
Viorel-1 answered

I think that since ValueType is a class, your code creates three different objects (instances). Although, the content of these instances is similar.

Calling ‘!=’ on different objects (references) gives True. (It does not compare the contents of the objects in this case).

Calling Equals returns True because it is designed to compare the contents.

See also: “Boxing”.

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.