NofBar
NofBar

Reputation: 116

Weird serialization error when entity is serializable

I get the following error when trying to serialize an object:

Type
'TEST.Common.TestObj`1+<>c__DisplayClass1`1[[TEST.Common.TestEntity,
TEST.Common, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=null],[System.Boolean, mscorlib, Version=4.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089]]' in Assembly
'Test.Common, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'
 is not marked as serializable.

I have the [Serializable] attribute both on the TestObj entity, all it's base entities and all entities related to their properties. What else can cause this "is not marked as serializable" error?

And what does c__DisplayClass1`1 even means??

Upvotes: 0

Views: 1853

Answers (2)

Adam Tal
Adam Tal

Reputation: 5961

Googled your c_DisplayClass1'1 and found the following:

http://rantdriven.com/post/2011/07/09/The-Mysterious-2b3c3ec__DisplayClass1.aspx

It has some links and explanations about how it might be an event handler you're trying to serialize.

This seems to be an helpful comment:

The main issue has to do with what's being serialized. By default, event handlers are internally represented by a compile-time generated field. This field holds a reference to the delegate(s) to be invoked when the event is raised.

Using your example above, the exception is caused because you're using an anonymous method that accesses resources beyond its defined scope. Under the covers, a class (probably called "<>c__DisplayClass1") is created to represent the anonymous method. This method doesn't get marked with the [Serializable()] attribute. When you attempt to serialize your object it attempts to serialize its fields and the exception is thrown.

You can fix your code in one of several ways:

If you want to maintain serialization on the event (which is on by default for a Serializable class), the easiest thing to do is to move your 'addedMessage' variable into the anonymous method so that it doesn't access any local variables in the containing scope.

If serialization of the event isn't important to you, you can declare your event field manually, marking it with the [NonSerialized()] attribute and then use the add and remove accessors on the event block to manage delegate references.

Upvotes: 5

Mike Zboray
Mike Zboray

Reputation: 40808

You are trying to serialize a compiler generated closure class which is not marked as serializable. There is no way to have those annotated with the Serializable attribute.

Upvotes: 0

Related Questions