For a class to be serializable it needs to support serialization, e.g., tagged with the serializable attribute as shown in the sample class below:
[Serializable]
internal sealed class Person
{
internal Person(string name, int age, DateTime retirementDate)
{
this.Name = name;
this.Age = age;
this.RetirementDate = retirementDate;
}
internal string Name { get; private set; }
internal int Age { get; private set; }
internal DateTime RetirementDate { get; private set; }
}
Now all you need to do to serialize an instance of the Person class into a string is to create a method that takes an instance of some type, say a person, and returns a string:
internal string SerializeToString<T>(T objectToSerialize) where T : class
{
// instantiate an in-memory stream
using (MemoryStream stream = new MemoryStream())
{
// instantiate a formatter, e.g., binary, soap, etc.
SoapFormatter formatter = new SoapFormatter();
// serialize the object to the stream
formatter.Serialize(stream, objectToSerialize);
// read the stream into a byte array
int objectLength = Convert.ToInt32(stream.Length);
byte[] objectBytes = new byte[objectLength];
stream.Position = 0;
stream.Read(objectBytes, 0, objectLength);
// convert the byte array into a string
return Encoding.Default.GetString(objectBytes);
}
}
By the same concept, just do the reverse to deserialize a string back into an instance of the type:
internal T DeserializeFromString<T>(string objectString) where T : class
{
// instantiate an in-memory stream
using (MemoryStream stream = new MemoryStream())
{
// instantiate a formatter, e.g., binary, soap, etc.
SoapFormatter formatter = new SoapFormatter();
// write the object string to a byte array
stream.Write(Encoding.Default.GetBytes(objectString), 0, objectString.Length);
stream.Position = 0;
// deserialize the stream into an instance of T
return formatter.Deserialize(stream) as T;
}
}