Serialisation - The Common Way
The most common way you find on the internet of serialising objects to streams in C# is the
XmlSerialiser. Now, while this is a very good class to use it does have quite significant problems including the fact that it cannot serialise things such as color, font, timespan, etc. However, there is a better and often easier way of doing serialisation (that also doesn't require all the nasty
XmlInclude attributes)...
Binary Formatter
The
BinaryFormatter class is under the namespace:
System.Runtime.Serialisation.Formatters.Binary.
(It's no wonder hardly anyone finds it... ;P)
Anyway, it is far better as not only can it serialise any object (so far as I know) but you also don't need to; Specify type you are going to serialise/deserialise; Have
XmlInclude,
XmlIgnore and other such tags (nor have extra members of classes just to get things to serialise properly) in fact, all you need is the
Serialisable attribute on any class you wish to serialise. I'll give a simple example:
namepsace Test
{
[Serialisable]
class TestClass
{
public Color AColor = Color.Black;
public TestClass()
{
}
public static void Serialise(string Filename, TestClass TheObj)
{
TheObj.AColor = Color.Red;
BinaryFormatter Ser = new BinaryFormatter();
FileStream TheStream = new FileStream(Filename);
Ser.Serialize(TheStream, TheObj);
TheStream.Close();
}
public static TestClass Deserialise(string Filename)
{
TestClass RetClass = null;
BinaryFormatter Ser = new BinaryFormatter();
FileStream TheStream = new FileStream(Filename);
RestClass = (TestClass)(Ser.Deserialize(TheStream));
return RestClass;
}
}
}
So you can see (hopefully) that this is better than
XmlSerialisation and can be adapted for any object and you don't need to use
FileSTream either if you don't want to. I use a similar thing to the above but using a
MemoryStream to serialise messages sent over a network.
BinaryFormatter is a far more powerful and, so far as I can tell, faster class that cuts out a lot of the
XmlSerialiser mess. :D
Hi there, so you're reading this? I probably ought to tell you something helpful then...
Okay well, I'm 17 from London, UK and I have been programming since I was 8 years old. You'll see from my profile I've dabbled in a lot of different areas and I do know what I'm talking about so as they say "gimme some respect yeah?"

I've done GCSE's (got 7A*'s, 2A's and a B in French) and am now studying for my AS-Levels (Math, Further Maths, Physics and Chemistry). My main aim is to go to university to study electronic engineering and then work in robotics (preferably humanoid but most of the field is interesting).
I have recently launched my website www.slidemyway.co.uk so please head over and take a look! All support and feedback is welcome!
Thanks for reading,
Edward Nutting