Formatting .NET Objects for Serialization
by Dino Esposito

Listing One
[Serializable]
public class Employee 
{
   public string LastName;
   public string FirstName;
}


Listing Two 
(a)
Employee emp = new Employee();
emp.LastName = "Davolio";
emp.FirstName = "Nancy";

FileStream fs;
fs = new FileStream("emp.dat", FileMode.Create);
BinaryFormatter bin;
bin = new BinaryFormatter();
bin.Serialize(fs, emp);                        
fs.Close();

(b)
Employee emp;
emp = (Employee) bin.Deserialize(fs);


Listing Three

[Serializable]
public class Employee 
{
   [NonSerialized]
   public int ID;
   public string LastName;
   public string FirstName;
}


Listing Four

// emp is Employee
SurrogateSelector ss = new SurrogateSelector();
MySurrogate sur = new MySurrogate();
ss.AddSurrogate(typeof(Employee), 
  new StreamingContext(StreamingContextStates.All), sur);
formatter.SurrogateSelector = ss;
formatter.Serialize(stream, emp);





1


