#795 – Rules for Creating an Immutable Class

There are times when it’s desirable to make a class immutable–meaning that client code cannot change any of the class’ data, after an instance of the class is created.

To create an immutable class:

  • Pass all the data that the class requires into a constructor
  • Make a copy of any mutable data type passed into the constructor
  • Make all properties read-only
  • Remove all public fields or make them readonly
  • Ensure that no methods change any of the data in the class
  • Ensure that properties or methods return a copy of any mutable data type that they return
  • Your type should inherit only from another immutable type

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

2 Responses to #795 – Rules for Creating an Immutable Class

  1. Pingback: #801 – An Example of a Simple Immutable Class | 2,000 Things You Should Know About C#

  2. Pingback: Replacing Unity3d’s core architecture: Structs | T-machine.org

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 )

Facebook photo

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

Connecting to %s

%d bloggers like this: