21147 C# ---Understanding

Implementing IClonable for Deep Copies
-------------------------------------------------------------------------------------
Lets say we have a class Person which refers to another class called Address . Person class contains the reference to Address class.The below is an example
of implementing IClonable into classes Person and Address so that one can use clone method to us the deep copy


public class Person : IClonable
{
    public string LastName { get; set};
    public string FirstName { get ; set};
    public Address personAddress {get ; set}

    public object clone()
    {
         Person newperson=(Person)this.MemberwiseClone();
        newperson.personAddress=(Address).this.personAddress.Clone();
        return newperson;
    }
}


   
public class Address : IClonable
{
    public int housenumber {get; set};
    public string streetname {get; set};

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

Person newperson=(Person)oldperson.Clone();


A type can choose to implement the ICloneable interface, which includes the single Clone method.  The intent of the Clone method is to create a copy of the object.
The simplest way to create a copy of the object is to call the Object.MemberwiseClone method.


public class Person : ICloneable
{
    public string LastName { get; set; }
    public string FirstName { get; set; }
    public Person(string lastname, string firstname)
    {
        LastName = lastname;
        FirstName = firstname;
    }

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


However, if the type contains members that are reference types, you’ll have to do more in order to get a deep copy.

Comments

Popular posts from this blog

Authentication and Authorization in Web API -Part1

My Gardening Journey 6