Using binary formatting for 1st time in .net C#
Code from MSDN is like this:
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("MyFile.lvl", FileMode.Create, FileAccess.Write,FileShare.None);
formatter.Serialize(stream, Globals.CurrentLevel);
stream.Close();
Just wondering should I store an IFormatter
in a field in my class and use it over and over again or should I do as above and instantiate a new one every time I save/load something?
I noticed it is not IDisposable
.
In binary serialization, the public and private fields of the object and the name of the class, including the assembly containing the class, are converted to a stream of bytes, which is then written to a data stream. When the object is subsequently deserialized, an exact clone of the original object is created.
The class BinaryFormatter in C# performs the actions of “serialization” and “deserialization” of binary data. It takes simple data structures such as integers (int), decimal numbers (float), and collections of letters and numbers (string) and can convert them into a binary format.
Microsoft warns against using BinaryFormatter (they write that there is no way to make the de-serialization safe). Applications should stop using BinaryFormatter as soon as possible, even if they believe the data they're processing to be trustworthy.
BinaryFormatter is used to serialize an object (meaning it converts it to one long stream of 1s and 0s), and deserialize it (converting that stream back to its usual form with all data intact), and is typically used with to save data to the hard disk so it can be loaded again after the game is closed and started up ...
There's very little overhead in re-creating a BinaryFormatter
, most of the properties it sets in the constructor are enum
s, see here (thanks to Reflector):
public BinaryFormatter()
{
this.m_typeFormat = FormatterTypeStyle.TypesAlways;
this.m_securityLevel = TypeFilterLevel.Full;
this.m_surrogates = null;
this.m_context = new StreamingContext(StreamingContextStates.All);
}
If you were going to re-use it though, you'd need to synchronize access to the Serialize
and Deserialize
methods to keep them thread-safe.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With