Have you failed a job interview?
Send us your job interview questions and get correct answers.

BP13: Defensive copies of objects

Always return defensive copies of objects that aren't immutable if you don't intend for the user of your API to make changes to them.

In C#, structs are a value type so you don't need to make a defensive copy of them. You need to make clones and/or copy constructors of classes to make defensive copies.

However, collections in particular have a bunch of special methods to handle it: In C#

  • Array.AsReadOnly(T[]) is a static method that will return a ReadOnlyCollection that is a wrapper around the array
  • List has .AsReadOnly() to wrap it in a ReadOnlyCollection
  • For Dictionaries, you can instantiate ReadOnlyDictionary directly; its constructor takes an IDictionary

Comments

No Comments Yet.
Be the first to tell us what you think.

Download Better Coder application to your phone and get unlimited access to the collection of enterprise best practices.

Get it on Google Play