Posted by: Cirilo Meggiolaro | 01/15/2009

Tip of the day #93 – Immutable classes

Immutable classes are that ones that cannot be changed after its instantiation. Easy concept but how do we create them?

When creating immutable classes you need to ensure that the properties are read-only and there is no access to fields or methods that directly or indirectly updates the property values.

The idea is to create a class named Customer with two properties: ID and Name. You may realize when checking the code that I am using auto-implemented properties. The idea behind the auto-implemented properties is to let the compiler creates a private object to store the value represented by the property. Once we need to expose read-only properties I am using a private set in the properties. 

Check the following examples.

Example 1 – Using a public constructor

The example 1 uses a public constructor to receive the values and populate the properties. This is the easiest way to perform that.

    public class Customer
    {
        public int ID { get; private set; }
        public string Name { get; private set; }

        public Customer(int id, string name)
        {
            this.ID = id;
            this.Name = name;
        }
    }

Example 2 – Using a static method to create the instance

The following example creates a class with a private constructor and read-only properties. In this case we expose a static method responsible for retrieve a new instance of the customer class.

    public class Customer
    {
        public int ID { get; private set; }
        public string Name { get; private set; }

        private Customer(int id, string name)
        {
            this.ID = id;
            this.Name = name;
        }

        public static Customer CreateCustomer(int id, string name)
        {
            return new Customer(id, name);
        }
    }

Advertisements

Responses

  1. Very good. I liked the private set.


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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

Categories

%d bloggers like this: