What is Clone ?
It look like duplicate of original
Reference is same for string
And different for objects
Once clone create it acts as independent 


class SiteName : Icloneable
    {

        private string SiteDomain { get; }
        private string Protocal { get; }

        public SiteName(SiteName siteName)
        {
            this.Protocal = siteName.Protocal;
            this.SiteDomain = siteName.SiteDomain;
        }

        public SiteName(string SiteName)
        {
            SiteDomain = SiteName.Split('.')[2];
            Protocal = SiteName.Split('/').FirstOrDefault();
        }

        public string showData
        {
            get { return $"Domain={SiteDomain} Protocal={Protocal}"; }
        }
           
        public object Clone()
        {
//Runtime exception : System.StackOverflowException  HResult=0x800703E9
//  Message=Exception of type 'System.StackOverflowException' was thrown.
            //return Clone();

// This will run as expected
            //return this.MemberwiseClone();

//Runtime exception : System.InvalidCastException
//Message=Unable to cast object of type 'System.String' to type 'Clone_Concept.SiteName'.
            //return showData;

            //return this.Clone();
            return MemberwiseClone();
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            //string clone
            string Site1Name = "http://www.abc.com";
            Console.WriteLine(Site1Name);
           
            string Site2Name = (string)Site1Name.Clone();
            Console.WriteLine(
                $"Reference {object.ReferenceEquals(Site1Name, Site2Name)}" +
                $"\n Is Equal {object.Equals(Site1Name,Site2Name)}");
            Console.WriteLine();
           
            //Object Clone
            SiteName siteNameObj1 = new SiteName(Site1Name);
            Console.WriteLine(siteNameObj1.showData);
           
            SiteName siteNameObj2 = (SiteName)siteNameObj1.Clone();
            Console.WriteLine(
                $"Reference {object.ReferenceEquals(siteNameObj1, siteNameObj2)}" +
                $"\n Is Equal {object.Equals(siteNameObj1, siteNameObj2)}");

            Console.Read();
        }
    }

No comments

sblog4u. Powered by Blogger.

Topics

Real World Programming Concept in 2 mins

Clone

What is Clone ? It look like duplicate of original Reference is same for string And different for objects Once clone crea...