I have a class that started life being mutable, but I’ve since made it immutable. Should I change it to be a struct? What sort of considerations go into choosing one over the other? My particular case is a Point type class (it represents a coordinate in a custom coordinate system) that is made up of 4 int fields, plus a few properties to access the same data in different ways. I note that String is a class and is immutable, so there must be some use-case for this.
I have a class that started life being mutable, but I’ve since made it
Share
Generally, no, you should not change it to a struct. Just because it’s immutable doesn’t mean that it’s automatically a good candidate for being a struct.
A struct should be small. With your four ints it’s just at the recommended limit of 16 bytes where performance for structs starts to degrade.
A struct should represent a single entity of some kind. Perhaps your class does that, but from your description it doesn’t sound likely.
A structure is harder to implement correctly than a class. It should behave well to things like comparisons, so there are more things to implement than what is expected of a class.
Unless you have a really good reason to implement it as a struct, like performance issues, you should keep your class as a class.