// Example 16-22
using System;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;

class Program
{
    static void Main(string[] args)
    {
        var bart = new Person { Name = "Bartek" };
        var millhouse = new Person { Name = "Milewski" };
        var ralph = new Person { Name = "Rafał" };
        var wigglePuppy = new Person { Name = "szczeniaczek" };

        bart.Friends.Add(millhouse);
        bart.Friends.Add(ralph);
        millhouse.Friends.Add(bart);
        ralph.Friends.Add(bart);
        ralph.Friends.Add(wigglePuppy);

        Console.WriteLine("Originał: {0}", bart);
        Console.WriteLine("Originał: {0}", millhouse);
        Console.WriteLine("Originał: {0}", ralph);

        var stream = new MemoryStream();
        var serializer = new BinaryFormatter();
        serializer.Serialize(stream, bart);

        Person bartCopy;
        stream.Seek(0, SeekOrigin.Begin);
        bartCopy = (Person) serializer.Deserialize(stream);

        Console.WriteLine("Czy kopia Bartka jest tym samym obiektem? {0}",
                           object.ReferenceEquals(bart, bartCopy));
        Console.WriteLine("Kopia: {0}", bartCopy);

        var ralphCopy = bartCopy.Friends.Single(f => f.Name == "Rafał");
        Console.WriteLine("Czy kopia Rafała jest tym samym obiektem? {0}",
                           object.ReferenceEquals(ralph, ralphCopy));
        Console.WriteLine("Kopia: {0}", ralphCopy);

    }
}
