#801 – An Example of a Simple Immutable Class

You sometimes want to make a class immutable–meaning that you can’t change any instance data in an object after it is created.

Below is an example of a simple class, created using the guidelines for creating an immutable class.

    public class ImmutableDog
        // All properties are read-only
        public string Name { get; private set; }
        public int Age { get; private set; }

        // Return copy of any mutable data
        //   (assuming that DogCollar is mutable)
        private DogCollar collar;
        public DogCollar Collar
            get { return (DogCollar)collar.Clone(); }

            private set
                if (collar != value)
                    collar = value;

        // All data that we need is passed into constructor
        public ImmutableDog(string name, int age, DogCollar collar)
            Name = name;
            Age = age;

            // Make copy of any mutable data passed in
            Collar = (DogCollar)collar.Clone();

        // Methods don't change instance data
        public void DoSomething()
            Console.WriteLine(string.Format("Hi, I'm {0}, aged {1}", Name, Age));