Implementing Value Types – Best Practices

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!

One Comment on “Implementing Value Types – Best Practices

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 )

Google+ photo

You are commenting using your Google+ 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 )

w

Connecting to %s

%d bloggers like this: