2

If reference type doesn't overload an equality operator ==, then build-in equality operator on Object will be used instead. Why isn't the same true for user-defined structs:

struct A{ } static void Main(string[] args) { A a = new A(); A a1 = new A(); bool equal= (a == a1); //error } 

Namely, doesn't ValueType ( from which all structs derive ) also overload == operator?

1
  • judging by the fact that youre getting an error, i would say no. Commented May 12, 2011 at 19:29

2 Answers 2

5

How would such a default == operator work? For reference types, comparing adresses is reasonable, but since that check will never be true for two ValueTypes (since if two ValueTypes are in scope then they are guaranteed to have different locations on the stack,) address comparison is pointless.

As the compiler has helpfully pointed out, ValueType very intentionally does not have a default == operator.

Sign up to request clarification or add additional context in comments.

5 Comments

@dlev, then how would you explain the fact that you can write bool equal = (5 == 6);. After all Int32 is a value type as well.
@Darin, would you consider that == the "default", insofar as the two Int32's are being compared without consideration for their Int32-ness?
@Darin: that's because some value types, like Int32, override ==. It still isn't default.
"How would such a default == operator work?" - by calling the default Equals member.
@Darin the reason that you can write bool equal = (5 == 6); is that the C# compiler translates the == operator into a ceq IL instruction. System.Int32 doesn't define any operators.
4

Structs probably don't provide a default == operator implementation because, unlike a class instance, a struct has no concept of reference-style identity.

From the guidelines:

Implementing the Equality Operator (==) on Value Types

In most programming languages there is no default implementation of the equality operator (==) for value types. Therefore, you should overload == any time equality is meaningful.

You should consider implementing the Equals method on value types because the default implementation on System.ValueType will not perform as well as your custom implementation.

Implement == any time you override the Equals method.

However, structs do provide a default Equals Method implementation which will do a memberwise compare using reflection.

3 Comments

No, there is no default for structs. There is an Equals and an == for anonymous types.
You've mis-read what I posted. There definitely is a default Equals method implementation for structs, but not an == operator implementation.
I've edited it to place emphasis on the method in case it's not clear enough, cheers.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.