Implementing Value Types – Best Practices

iReadable { }

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…

View original post 43 more words

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s