[Serializable] objects and Exceptions

  • Thread starter Thread starter Garrett
  • Start date Start date
G

Garrett

The following quote

The only requirement placed on object graphs is that all objects referenced
by the object that is being serialized must also be marked as Serializable
(see Basic Serialization). If this is not done, an exception will be thrown
when the serializer attempts to serialize the unmarked object.

appears at
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dndotnet/ht
ml/objserializ.asp

However when I run code which tried to serialize an object, no exception was
thrown. Instead the
code just seemed to hang. (version 1.1)

Anyone know what's wrong?

Thanks.
Garrett

Sample code follows:

using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

//[Serializable]
public class Stuff{
public String Name;
}


class Test {
[STAThread]
static void Main(string[] args) {
Stuff mystuff = new Stuff();
mystuff.Name = "Try this";
MemoryStream ms = new MemoryStream(); //memory stream
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(ms, mystuff);

ms.Position = 0;
Stuff s = (Stuff)bf.Deserialize(ms);
Console.WriteLine(s.Name);
}
}
 
Oops, I forgot to say no exception is being thrown when the class to be
serialized
is NOT marked as [Serializable] which is the point of the above question.
 
Garrett said:
Oops, I forgot to say no exception is being thrown when the class to
be serialized
is NOT marked as [Serializable] which is the point of the above
question.

I have tried your code on .NET 1.1 and if the class is marked with
[Serializable] then it works OK, but if I comment out the attribute I get a
SerializationException thrown:

Unhandled Exception: System.Runtime.Serialization.SerializationException: T
pe Stuff in Assembly ser, Version=0.0.0.0, Culture=neutral, PublicKeyToken=
is not marked as serializable.

Does the code you copied come from some other (larger) application? I ask
because maybe you have a App Domain exception handler, or maybe if its a GUI
code, you have a thread exception handler that is catching the exeption? If
you add code like this:

throw new Exception("Test");

do you find that this exception is thrown?

Richard
 
Back
Top