Cloning Immutable Objects

Problem
You want to know how to clone immutable objects.

Solution
Use the Clone method to return a reference to the object itself.

Comments
How do you know if a type’s immutable? It’s immutable if client code can only initialize its fields and properties at creation time. Examples of immutable types are delegates and strings.

Example

// An immutable object.
public class Point : ICloneable {
    public readonly double X;
    public readonly double Y;

    public Point(double x, double y) {
        this.X = x;
        this.Y = y;
    }

    // The Clone method returns a reference to self.
    public object Clone() {
        return this;
    }
}

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