2

If there is an object in which every public property must be serialized and properties are simple (just numbers or strings or objects already implementing ISerializable), is there an easy way to do it without having to create GetObjectData(SerializationInfo info, StreamingContext context) and a constructor taking SerializationInfo as argument every time?

I know that it can be done manually with reflection, but is there a magic method inside the .NET Framework to do it?


So the correct answer is:

Don't try to implement ISerializable - it is for custom serialization. Instead add the [Serializable] attribute right before your class declaration.

Arseni Mourzenko
  • 50,338
  • 35
  • 112
  • 199

1 Answers1

4

Try the BinaryFormatter class - should do what you need

EDIT: You do not derive from BinaryFormatter - it is a utility class you use to do your serialization. Here is an example copied from the docs

MyObject obj = new MyObject();
obj.n1 = 1;
obj.n2 = 24;
obj.str = "Some String";
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("MyFile.bin", FileMode.Create, FileAccess.Write, FileShare.None);
formatter.Serialize(stream, obj);
stream.Close();
Ray
  • 21,485
  • 5
  • 48
  • 64
  • Agreed. Here's a link to the docs: http://msdn.microsoft.com/en-us/library/system.runtime.serialization.formatters.binary.binaryformatter.aspx – kbrimington Aug 07 '10 at 03:04
  • What do I need precisely to do? It seems impossible to derive from `BinaryFormatter`, since it is sealed. Do I have to pass specific argument to `Serialize`/`Deserialize`? – Arseni Mourzenko Aug 07 '10 at 03:13
  • In my case, if `MyObject` does not implement `ISerializable` interface, it cannot be serialized. If it implements it, the compiler requests to create to create `GetObjectData(SerializationInfo info, StreamingContext context)` and a constructor taking `SerializationInfo` as argument. What I'm doing wrong? – Arseni Mourzenko Aug 07 '10 at 14:33
  • 2
    Don't try to implement ISerializable - it is for custom serialization. Instead add the [Serializable] attribute right before your class declaration. – Ray Aug 07 '10 at 15:39