- Add the SerializableAttribute to the class.
- Have the class implement the ISerializable interface.
- Request sufficient privileges for your GetObjectData() implementation.
In essence you are rolling custom serialization. And here is how Foo would look like with all these in place:
using System.Runtime.Serialization;
using System.Security.Permissions;
...
[Serializable]
public class Foo : ISerializable {
protected Foo(SerializationInfo info,
StreamingContext context) {
_barString = info.GetString("_barString");
_barInteger = info.GetInt32("_barInteger");
}
[SecurityPermissionAttribute(
SecurityAction.Demand,
SerializationFormatter = true)]
public virtual void GetObjectData(SerializationInfo info,
StreamingContext context) {
info.AddValue("_barString", _barString);
info.AddValue("_barInteger", _barInteger);
}
private string _barString;
private int _barInteger;
}
Note that the constructor is protected. This way it cannot be called except from the serialization code within .NET. It is however accessible by code in subclasses.
If your class is derived from a class that implements ISerializable, then you need to call the base class in both the constructor and the GetObjectData() implementation as follows:
[Serializable]
public class Foo : Base { // Base implements ISerializable
protected Foo(SerializationInfo info,
StreamingContext context)
: base(info, context) {
// your deserialization code
}
[SecurityPermissionAttribute(
SecurityAction.Demand,
SerializationFormatter = true)]
public virtual void GetObjectData(SerializationInfo info,
StreamingContext context) {
base.GetObjectData(info, context);
// your serialization code
}
}
For more information please check MSFT's web site here.
Very helpful, thanks!
ReplyDeleteThat was my problem, thanks!
ReplyDeleteThanks. This was helpful for my team.
ReplyDeleteHelped me out alot, thanks!
ReplyDeleteManfred,
ReplyDeleteThanks a lot for the post, it did help as my exception is thrown across app domain
Jack
hi there... THANKS A LOT!
ReplyDeletebpbrainiak
Thanks ...
ReplyDeleteYou literally save the day.
Thurein
It is 10:30PM on a Friday night and I can go home and play XBox 360 now because I found your post. Thank you so much! Note: like the other poster this was being thrown across AppDomain.
ReplyDeleteThis was helpful. Thanks for the post.
ReplyDeleteThanks man - finally I got how serialization of custom classes works.
ReplyDelete