views:

179

answers:

2

I have a class that I want to be serializable but contains a public instance of delegate that, apparently can't be serialized:

<Serializable()> Class A
    Public Delegate Function TestEventHandler(ByVal myObj as CutomObject, _
                                         ByVal myObj2 as CustomObject) as Boolean

    ' does not 'want' to be serialized - cause: no parameterless constructor'
    Public TestDelegate as TestEventHandler
End Class

I used <XmlIgnore()> _ and it helped - i mean the exception is not trowed at this member anymore.

Is there a way to make it serializable however?

+1  A: 

And your question is ?

It is quite understandable that a delegate cannot be serialized, since it can be seen as a 'function pointer' rather then real data.

You can solve your problem by applying the NonSerialized attribute to that delegate.

[Serializable]
public class Test
{
    [NonSerialized]
    public TestEventHandler TestDelegate;
}

But, remember that Xml Serialization requires other attributes then 'regular' serialization through the BinaryFormatter or SoapFormatter classes.

When you use XmlSerialization, you should use the XmlIgnore attribute. When you use XmlSerialization, you do not have to mark your class as Serializable. Instead, it should have a default public constructor. XmlSerialization only serializes public properties, that have a getter and a setter.
You can control the way your object is serialized via XmlSerialization by these attributes.

Frederik Gheysels
I use XmlSerialization, so NonSerialized does not help. I used <XmlIgnore()> _ adn it helped. Now, is there a possibility to serialize the delegate however?
serhio
@Frederik: `[NonSerialized]` doesn't work with XML Serialization.
John Saunders
That's what I'm saying: there's a difference between XmlSerialization and regular serialization.From the Topicstarts openingpost, it was not really clear what kind of serialization he used, when I answered the question.
Frederik Gheysels
+1  A: 

Use [XmlIgnore] on the delegate.


No, there's no way to serialize a delegate. What would it even look like, and what would a platform other than .NET do with it?

John Saunders
thanks, helped. Is there a way to serialize it however?
serhio