Home   Cover Cover Cover Cover
 

ISerializable

/csbook/solutions/15/A03.cs
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;


[Serializable]
// objects of this class should be serialized such that only the
// day, month and year of a date are written but not the time.
class Node: ISerializable {
  public DateTime date;
  public Node next;
  
  public Node(DateTime d) { date = d; }
  
  // this constructor is automatically called during deserialization
  public Node(SerializationInfo info, StreamingContext context) {
    // read year, month and day and convert it to the DateTime field
    int year  = (int)info.GetValue("year", typeof(int));
    int month = (int)info.GetValue("month", typeof(int));
    int day   = (int)info.GetValue("day", typeof(int));
    date = new DateTime(year, month, day);
    // read the next field
    next = (Node)info.GetValue("next", typeof(Node));
  }
  
  // this method is automatically called during serialization
  public void GetObjectData(SerializationInfo info, StreamingContext context) {
    info.AddValue("year", date.Year);
    info.AddValue("month", date.Month);
    info.AddValue("day", date.Day);
    info.AddValue("next", next);
  }
}


[Serializable]
class List {
  Node head = null;
  
  public void Add(DateTime date) {
    Node p = new Node(date);
    p.next = head; head = p;
  }
  
  public bool Contains(int date) {
    Node p = head;
    while (p != null && date.CompareTo(p.date) != 0) p = p.next;
    return p != null;
  }
  
  public void Print() {
    Node p = head;
    while (p != null) {
      Console.WriteLine(p.date);
      p = p.next;
    }
  }
}


public class Test {

  static void Main() {
    //----- build the list
    List list = new List();
    list.Add(new DateTime(2003, 4, 25, 10, 30, 0));
    list.Add(new DateTime(2003, 3, 5, 12, 24, 30));
    list.Add(new DateTime(2003, 1, 20, 11, 11, 11));
    list.Print();

    //----- serialize the list
    FileStream s = new FileStream("myfile", FileMode.Create);
    IFormatter f = new BinaryFormatter();
    f.Serialize(s, list);
    s.Close();

    //----- deserialize the list
    s = new FileStream("myfile", FileMode.Open);
    List newList = f.Deserialize(s) as List;
    s.Close();
    if (newList != null) newList.Print();
  }
}