Translate

Wednesday, August 14, 2013

C# deep copy object


using System.IO;
using System.Runtime.Serialization;

namespace ConsoleApplication29
{
    class Program
    {

        static void Main(string[] args)
        {
            var dog = new Dog { Age = 2, IsBig = true };

            Dog dogCopy;

            var ds = new DataContractSerializer(typeof(Dog));

            using (var s = File.Create("Dog.xml"))
            {
                ds.WriteObject(s, dog);//Serialize into an xml file
            }

            using (var s = File.OpenRead("Dog.xml"))
            {
                dogCopy = (Dog)ds.ReadObject(s);//Deserialize from an xml file and cast into an object
            }
        }

    }

    public class Animal
    {
        public int Age { getset; }

    }

    public class Dog : Animal
    {
        public bool IsBig { getset; }

    }
}


No comments:

Post a Comment

Comments will appear once they have been approved by the moderator