#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));
        }
    }
Advertisements

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

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s

%d bloggers like this: