fooObj obj1 = new fooObj() { Name = "Aval" };
fooObj obj2 = (fooObj)obj1.Clone();
fooObj obj3 = (fooObj)obj1.CloneWithSerialization();
fooObj obj4 = obj1;
fooObj obj5 = (fooObj)obj1.ShallowCopy();
System.Diagnostics.Debug.WriteLine(obj1 == obj2);
System.Diagnostics.Debug.WriteLine(obj1 == obj3);
System.Diagnostics.Debug.WriteLine(obj1 == obj4);
System.Diagnostics.Debug.WriteLine(obj1 == obj5);
System.Diagnostics.Debug.WriteLine(obj1.Equals(obj2));
System.Diagnostics.Debug.WriteLine(obj1.Equals(obj3));
System.Diagnostics.Debug.WriteLine(obj1.Equals(obj4));
System.Diagnostics.Debug.WriteLine(obj1.Equals(obj5));

[Serializable]
    class fooObj: ICloneable, ISerializable
    {
        public String Name { get; set; }

        public override bool Equals(object obj)
        {
            if (obj == this)
                return true;
            else if (obj == null)
                return false;
            else 
                return (obj.GetType() == typeof(fooObj) && this.Name.Equals(((fooObj)obj).Name));
        }

        public override int GetHashCode()
        {
            return base.GetHashCode();
        }

        public object Clone()
        {
            return new fooObj() { Name = this.Name };
        }

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

        public object CloneWithAs()
        {
            return (new fooObj(){Name=this.Name}) as object;
        }

        public object ShallowCopy()
        {
            return this;
        }

        public object CloneWithSerialization()
        {
            using (Stream objects = new MemoryStream())
            {
                IFormatter formatter = new BinaryFormatter();
                formatter.Serialize(objects, this);
                objects.Seek(0, SeekOrigin.Begin);
                return formatter.Deserialize(objects);
            }
        }

        public fooObj() { }

        #region ISerializable Members

        [SecurityPermissionAttribute(SecurityAction.Demand,
          SerializationFormatter = true)]
        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            info.AddValue("Name", this.Name);
        }

        protected fooObj(SerializationInfo info, StreamingContext context)
        {
            this.Name = info.GetString("Name");
        }

        #endregion
    }
Advertisements