Yurttas/PL/OOL/CS/F/11/01/Serialize00.cs

From ZCubes Wiki
Jump to navigation Jump to search
  1/**
  2 *  Copyright(C) 2004
  3 *  All Rights Reserved. Salih Yurttas, ZCubes, BitsOfCode Software Systems, Inc..
  4 *
  5 *  Permission to use, copy, modify, and distribute this
  6 *  software and its documentation for EDUCATIONAL purposes
  7 *  and without fee is hereby granted provided that this
  8 *  copyright notice appears in all copies.
  9 *
 10 *  @date   : January 1, 2004.
 11 *  @author : Salih Yurttas, Yi Yang.
 12 */
 13
 14
 15using System;
 16using System.IO;
 17using System.Runtime.Serialization;
 18using System.Runtime.Serialization.Formatters.Binary;
 19
 20namespace Serialization00
 21{
 22
 23  public class Serialize00
 24  {
 25    public static void Main(string[] args)
 26    {
 27      Serialize00 sObject = new Serialize00();
 28
 29      Employee e = new Employee("Tom",
 30                                "male");
 31
 32      Console.WriteLine("Serializing employee to master.ser");
 33
 34      sObject.Serialize("master.ser", e);
 35
 36      Console.WriteLine("Deserializing employee from master.ser");
 37
 38      Employee a = (Employee)sObject.Deserialize("master.ser");
 39
 40      Console.WriteLine(a.Name + " : " + a.Gender);
 41    }
 42
 43    public void Serialize(string filename,
 44                          Employee e)
 45    {
 46      FileStream fStream = new FileStream(filename,
 47                                          FileMode.Create);
 48
 49      BinaryFormatter bFormatter = new BinaryFormatter();
 50
 51      bFormatter.Serialize(fStream, e);
 52
 53      fStream.Close();
 54    }
 55
 56    public object Deserialize(string filename)
 57    {
 58      FileStream fStream = new FileStream(filename,
 59                                          FileMode.Open);
 60      BinaryFormatter bFormatter = new BinaryFormatter();
 61
 62      object o = bFormatter.Deserialize(fStream);
 63
 64      fStream.Close();
 65
 66      return o;
 67    }
 68  }
 69
 70  [Serializable]
 71  public class Employee
 72  {
 73    private string name;
 74    private string gender;
 75
 76    public string Name
 77    {
 78      get
 79      {
 80        return name; 
 81      }
 82      set
 83      {
 84        name = value; 
 85      }
 86    }
 87
 88    public string Gender
 89    {
 90      get 
 91      {
 92        return gender;
 93      }
 94      set
 95      {
 96        gender = value;
 97      }
 98    }
 99 
100    public Employee()
101    {
102    }
103 
104    public Employee(string name,
105                    string gender)
106    {
107      Name = name;
108      Gender = gender;
109    }
110
111    public void Retire()
112    {
113      Console.WriteLine("I retired");
114    }
115  }
116
117}