Serialization will not deserialize delegates to non-public methods

A

adospace

Sometimes deserialization throws an exception as shown in subject. I'm
confused because this happens when I deserialize an object from a file and
it seems to be random. Does exist a cause for this problem? Should I prefer
to implement ISerializable interface for each class I need serialization?

Thanks in advance!
 
G

Guest

Even though the method is non-public, the delegate itself is a first class object which does not support serialization, therefore you will have to declare the delegate protected or private and make accessor methods to assign it. If the delegate declaration is public, your class will not serialize.
 
A

adospace

I know why code like as shown below throws that exception, but I don't know
how to prevent it. If I make private or protected the delegate declaration I
can't define public the event accessor obviously. Any hints?

[Serializable]
class Class2
{
public delegate void MyDelegateFunc(int i);
private event MyDelegateFunc myEvent;
public event MyDelegateFunc AccessMyEvent
{
add
{
myEvent += value;
}
remove
{
myEvent -= value;
}
}
}

/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
Class2 c = new Class2();

c.AccessMyEvent +=new
DelegateTest.Class2.MyDelegateFunc(c_AccessMyEvent);

BinaryFormatter bf = new BinaryFormatter();
FileStream fs = new FileStream("test.dat",FileMode.Create);

bf.Serialize(fs, c);

fs.Flush();
fs.Close();

fs = new FileStream("test.dat", FileMode.Open);

c = (Class2)bf.Deserialize(fs);

fs.Close();
}

public static void c_AccessMyEvent(int i)
{

}
}


Clayton Gulick said:
Even though the method is non-public, the delegate itself is a first class
object which does not support serialization, therefore you will have to
declare the delegate protected or private and make accessor methods to
assign it. If the delegate declaration is public, your class will not
serialize.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top