I am trying to learn to use C# serialization as a way to save objects into files that can be reloaded back into objects.
A plain class like this that I tested
[Serializable()]
public class PlainClass
{
public string Name;
private int Age;
protected decimal Price;
}
Can be directly BinaryFormatter.Serialize() and BinaryFormatter.Deserialize() without errors. (by the way, the private and protected properties also get serialized although the docs say only public)
But the moment it implements ISerialization or inherit some class like Hashtable that implements ISerialization, the you-know-what deserialization constructor is required. The word or concept of “implement” becomes a misnomer because Hashtable does not actually implement that constructor.
Is there a way to fall back to the “auto” Serialization/Deserialzation provided only by the attribute? Or is there an easier way to write info.GetValue() for a hundred properties in a class?
There is a lot of confusion in your post:
I suspect you are confusing two different serializers;
BinaryFormatteris and always has been documented as field-centric. It doesn’t distinguish between public/private, and it never looks at properties: only fields.XmlSerializer, by contrast, only looks at public properties and fields.Yes it does; it is a
protectedconstructor:If you inherit
Hashtableyou can chain to this constructor:Note, however, that you probably shouldn’t be using
Hashtablemuch unless you are on .NET 1.1.No; none.
In the case of inherited data, you could chain the base-constructor or switch to encapsulation instead of inheritance – either avoids the need to worry about data other than your own.
Note, however, that I almost always guide against
BinaryFormatter– it can be vexing, and is quirky with versioning. For every annoyance withBinaryFormatter, I use protobuf-net (I would, since I wrote it) – this generally makes serialization much more controlled (and more efficient), and includes anISerializablehook if you really want to useBinaryFormatter(i.e. it can useBinaryFormatteras the wrapper, but with a protobuf-net payload).