#520 – Choosing Between a struct and a Class

struct and a class both encapsulate data and methods in a new type.  When you are creating a new type, you’ll generally create a new class.  But there are cases when a struct is the better choice.

Create a struct, rather than a class, when all of the following is true:

  • You want value type semantics, that is–a variable of this type directly contains the data and a copy is made whenever you assign the value to a new variable or pass the variable to a method
  • Data stored in the struct won’t be modified after an instance is created or does not change very often
  • You don’t need to inherit from another type (a struct inherits only from System.ValueType)
  • You need to store only a small amount of data in the type
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

2 Responses to #520 – Choosing Between a struct and a Class

  1. Pranav Shah says:

    While reading this, I also came across “Parameter Object” refactoring.

    Here is a class example:
    class DateRange {
    DateRange (Date start, Date end) {
    _start = start;
    _end = end;
    }
    Date getStart() {
    return _start;
    }
    Date getEnd() {
    return _end;
    }
    private final Date _start;
    private final Date _end;

    boolean includes (Date arg) {
    return (arg.equals(_start) ||
    arg.equals(_end) ||
    (arg.after(_start) && arg.before(_end)));
    }

    The code and the articles is from: http://sourcemaking.com/refactoring/introduce-parameter-object

    I was wondering could this class be created as a Struct, and if that would be advantageous or not, with some explanation if possible.

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

%d bloggers like this: