Serialization with .NET - Serializing Custom Types
(Page 2 of 4 )
In the previous example, we serialized a string object. However, you are, of course, not limited to serializing types provided by the framework. The real purpose of serialization is to serialize your own types. Thankfully, the process of serializing custom types doesn't have to be difficult or complex. .NET itself does most of the work for you. All you have to do is tell it what can be serialized and what can't. This is done through attributes.
Let's take a look at a type called Person:
public class Person
{
private string name;
private int age;
public Person(string name, int age)
{
this.name = name;
this.age = age;
}
public string Name
{
get
{
return name;
}
}
public int Age
{
get
{
return age;
}
}
}
We can't simply serialize an instance of Person, or any other custom type. This is because not all types are fit for serialization. It simply wouldn't make sense for some types to be serialized. Instead, we must tell .NET that instances of our type can be serialized. This is done through the Serializable attribute:
[Serializable]
public class Person
{
...
}
Now we're free to serialize instances of our type. The process for doing this is the same as it was for serializing a string object earlier. We create a Stream object (a FileStream in our example) and a Formatter object (we'll use a BinaryFormatter again), and then we simply make a call to the Serialize method, passing the Stream and the object to be serialized. To deserialize, we call the Deserialize method. Here's everything in action:
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
class PersonSerialization
{
public static void Main(string[] args)
{
// Create a Person
Person bob = new Person("Bob", 35);
Console.WriteLine("{0}, age {1}.", bob.Name, bob.Age);
// Serialize our Person
FileStream myStream = File.Create("bob");
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(myStream, bob);
// Deserialize our Person
myStream.Position = 0;
bob = (Person)formatter.Deserialize(myStream);
myStream.Close();
Console.WriteLine("{0}, age {1}.", bob.Name, bob.Age);
}
}
Bob, age 35.
Bob, age 35.
Note that if we were to try to serialize a Person object without marking Person as Serializable, we would get a SerializationException:
Unhandled Exception: System.Runtime.Serialization.SerializationException:Type Person is not marked as Serializable.
...
Next: Serializing Only Some Internal Data >>
More .NET Articles
More By Peyton McCullough