❔ ✅ Struct equality
hi!
I have a struct such as this one:
What's the correct way to implement equality between two
InternerId
s based on _id
? I don't want equality with any other type except itself.27 Replies
Override
bool Equals(object? other)
and optionally implement IEquatable<InternerId>
You could also use a record struct, which implements equality by defaultI thought about this, but I'm not sure if/how that works with keeping the field private, the constructor internal, and the whole type public
I guess
Does that mean it's not possible? (sorry I'm not a native english speaker so it's not super clear what "I guess" means in this context 😅 )
No I meant your point is valid as to why you shouldn't use a record here, my bad
Ah ok I see. Thanks for the help 😄 I'll implement what you suggested 🙂
you can still use a record
in fact, this would do what you want
oh interesting! So, for the purpose of equality and such, records consider all their fields/properties?
the auto-generated equality is based on all the fields, right
ok yeah, that's good to know
definitely reduces boilerplate here
thanks!
you can reduce the boilerplate even further with a primary constructor
when you assign a primary constructor parameter directly to a field or property with the same name, it prevents the public property from being generated
it does sort of break the
_
convention. i think it is a dumb convention and you will run into pitfalls like this if you try to stick with it. but that is just my strong opinionI think this is slightly different though since the constructor would also be public (instead of
internal
?uh. oh
but still really good to know nonetheless
well then ignore all of that
I mean, it's still good to know in general
but yeah
is it?
yes
this includes auto-generated backing fields, of course
reflectronic
Try the /sharplab command! | React with ❌ to remove this embed.
you can look at the implementation of Equals here to see what is going on
ah
thought it only looked at props
So, just to be sure, for the purpose of the original question, this would be the way to go, right?
right
Alright, thank you both 🙂
by the way, is there a way to mark the thread as "solved"? 🤔
$close
Use the /close command to mark a forum thread as answered
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.