When implementing you own struct you should take into consideration the following:
- Use structs when you intend to create a great many of them
- structs should be small. Large structs (i.e. structs with many fields) would lead to poor performance, since structs are copied each time.
- Use structs when you require high density memory collections. Structs have have a much simpler memory layout and offer excellent memory density and lack of overhead
- Override structs Equals(…) method and implement IEquitable<T> interface to avoid boxing.
- Overload == and != operators
- Override GetHashCode method.
- structs should almost always be immutable. Actually I’ll go further and say always. Mutable structs could lead to confusion if declared as readonly. Any modifications to a mutable readonly struct will be ignored, making it a very difficult bug to spot.
Structs have also got their own limitations. Since they don’t have an object header, you cannot for example use a lock(…) on a struct since this will result on compile time error. However Monitor.Enter(…) accepts any object, structs included, thus leading to a bug. The value of the struct will be boxed each time and that would be equivalent to having no lock at all!
Reblogged this on denhul.
LikeLike