Reference Versus Value Types

Problem
You want to know when to use a structure over a class.

Solution
Consider using a structure instead of a class when all these criteria are true:
a. Your type does not need to inherit from a .NET Framework class.
b. You can seal the type. In other words, you will never need to inherit from the type.
c. You don’t need to initialize the type’s fields to any value other than their default state. This means zero for numbers and null for objects.
d. You expect assignments to copy the value and not the pointer to the object.
e. You don’t need a finalizer.

Also, consider using a structure rather than a class when one or more of the following criteria are true:
a. The type contains fields that need less than or equal to 16 bytes of memory.
b. The type’s fields are all value types.
c. The type does not need to implement interfaces.
d. You will rarely need to cast instances of the type to an interface variable.
e. You expect to have arrays with a large number of instances of the type.

Comments
When possible, prefer structures over classes due to their speed. Avoid structures if you expect to assign them to variables often. Avoid them if you plan to pass them by value to methods as well. Both of these scenarios will cause a lot of memory copy operations. Finally, a compilation error will occur if you attempt to define a destructor in a structure.

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 )

Connecting to %s