#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
Advertisements