Home

Built-In Interfaces: IClonable

     

Introduction

Copying an object consists of creating another sample of it and that contains the same values as the original. To make this operation available to your class, you can implement an interface named ICloneable. The ICloneable interface is defined in the System namespace of the mscorlib.dll library.

 

The ICloneable interface is equipped with one method named Clone. Its syntax is:

object Clone();

To assist you with making a copy of a variable, the Object class is equipped with a method named MemberwiseClone. This means that all classes of the .NET Framework and any class you create in your C# application automatically inherits this method. The syntax of this method is:

protected Object MemberwiseClone();

Therefore, when implementing the ICloneable interface, in your class, you can simply call the MemberwiseClone() method. Here is an example:

using System;

public class Square : ICloneable
{
    private double sd;

    public Square()
    {
        this.sd = 0.00;
    }

    public Square(double side)
    {
        this.sd = side;
    }

    public double Side
    {
        get
        {
            return sd;
        }

        set { sd = value; }
    }

    public double Perimeter
    {
        get
        {
            return sd * 4;
        }
    }

    public double Area
    {
        get
        {
            return sd * sd;
        }
    }

    public object Clone()
    {
        return this.MemberwiseClone();
    }
}

public class Exercise
{
     public static int Main()
     {
         Square sqr1 = new Square();
         sqr1.Side = 24.60;
         square Sqr2 = (Square)sqr1.Clone();

         Console.WriteLine("Square Characteristics");
         Console.WriteLine("-----------------------");
         Console.WriteLine("Side:      {0}", sqr1.Side);
         Console.WriteLine("Perimeter: {0}", sqr1.Perimeter);
         Console.WriteLine("Area:      {0}", sqr1.Area);
         Console.WriteLine("=-=-=-=-=-=-=-=-=-=-=-=");

         Console.WriteLine("Square Characteristics");
         Console.WriteLine("=---------------------=");
         Console.WriteLine("Side:      {0}", sqr2.Side);
         Console.WriteLine("Perimeter: {0}", sqr2.Perimeter);
         Console.WriteLine("Area:      {0}", sqr2.Area);
         Console.WriteLine("=======================\n");

         return 0;
     }
 }

This would produce:

Square Characteristics
-----------------------
Side:      24.6
Perimeter: 98.4
Area:      605.16
=-=-=-=-=-=-=-=-=-=-=-=
Square Characteristics
=---------------------=
Side:      24.6
Perimeter: 98.4
Area:      605.16
=======================

Press any key to continue . . .
 
 

Home Copyright © 2010-2011 FunctionX