0

in C# I know that if we try to compare two structs with "==" operator

    S1 structObj1 = new S1(); //while S1 is a struct
    S1 structObj2 = new S1();
    if(structObj1 == structObj2)
    {}

it will fire a compile error because structs are stored in the stack and the "==" operator compares references...

but why doesn't this apply when we compare two integers or chars which are struct objects? aren't they stored in stack too?

  • 3
    https://stackoverflow.com/questions/25461585/operator-overloading-equals – Rand Random Jan 29 '23 at 17:07
  • 4
    Integers and chars are *not* struct objects, it merely looks like they are when you look at .NET framework source. They are primitive types that a processor understands, and can compare easily with a dedicated machine code instruction. No such feature exists for structs. Technically it could have been implemented, but the code is expensive since equality is a type-specific property. The C# team does not like hiding expensive code underneath an innocent looking operator. Do consider the [*record* keyword](https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/types/records). – Hans Passant Jan 29 '23 at 17:15
  • 1
    Also any default method of evaluating equality would be ambiguous as soon as you consider structs with reference type members, like arrays or class instances. Would equality be measured by the identity of the references or their own underlying values? So rather than implement a default behavior that would be ambiguous they leave it to you to implement == only if you want to. – Emperor Eto Jan 29 '23 at 17:24
  • Side note: you may want to [edit] the question with links to docs (like https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/equality-operators) and SO articles (like https://stackoverflow.com/questions/4853213/are-structs-always-stack-allocated-or-sometimes-heap-allocated) so it is clear which misunderstandings demonstrated in the post you need help with. I'm not sure if duplicate I selected actually answers what *you think you are asking*, but to me it has the same answer as this one. – Alexei Levenkov Jan 29 '23 at 20:39

1 Answers1

0

Because == is an identity semantic operation.

If you override Equals() and make a struct comparison method inside of it, you'll be able to compare structs via. value semantics. Although I can't confirm the actual comparison result from doing that change.

Matbart
  • 63
  • 4