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?

4
  • 3
    stackoverflow.com/questions/25461585/… Commented Jan 29, 2023 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. Commented Jan 29, 2023 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. Commented Jan 29, 2023 at 17:24
  • Side note: you may want to edit the question with links to docs (like learn.microsoft.com/en-us/dotnet/csharp/language-reference/…) and SO articles (like stackoverflow.com/questions/4853213/…) 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. Commented Jan 29, 2023 at 20:39

1 Answer 1

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.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.