I ran into the same old "cannot serialize value myType of type myType" issue the other day and knew immediately that I should check that my classes were marked with the [Serializable] attribute.  Well, I checked and all of the classes had the attribute as required.  So I spent an hour our so searching the web for other reasons why we might get this error.  I found nothing.

So I pinged a buddy of mine and I walked him through the issue.  He said, "It's gotta be one of your classes missing the Serializable attribute.  Did you try writing a test to the serialization?"  For some reason I was avoiding writing this test, but I broke down and did it.

This is what I found.  You must be careful what classes you use to implement IEnumerable<T>.  List<T> will serialize okay, but there are others that will not.  In particular, my problem was with Enumerable<SelectIterator>.  It isn't marked serializable.  Where does this SelectIterator come from?  The Select extension method:

ids.Split( ',' ).Select( id => new Deal { Id = int.Parse( id ) } )

Of course there was a simple fix.

ids.Split( ',' ).Select( id => new Deal { Id = int.Parse( id ) } ).ToList()

The good news is now I have a test so if I forget why the ToList is there and remove it, my test will fail.  The next time I get an error, I will do the right thing... write a test to reproduce it.

posted on Wednesday, January 21, 2009 1:20 PM
Filed Under [ .Net Linq ASP.Net C# ]

Comments

Gravatar
# re: IEnumerable<T> Serialization
posted by Yvan
on 2/2/2009 7:49 PM
Hi Will,



I recently stepped on the same issue and, since i am new to TDD , I was wondering if you could tip me on how you tested this.

thx
BTW Is this your real name? ;-)
You must be as famous as the actor cause I got your blog straight of the to 5 of google on this issue!
Gravatar
# re: IEnumerable<T> Serialization
posted by Will
on 2/3/2009 8:48 AM
Hi Yvan,

Here is how I am testing the serialization of my entity objects after retrieving from the database. The same approach can be taken at any level.

using System.Runtime.Serialization.Formatters.Binary;
...
//get the data that we want to test for serialization
//I am really Will Smith
var targetData = GetMyData();

//try serializing, if an exception occurs, the test fails
//I have no desire to be as popular as the actor.
var formatter = new BinaryFormatter();
var writeStream = new System.IO.MemoryStream();
formatter.Serialize( writeStream, targetData );
Gravatar
# re: IEnumerable<T> Serialization
on 11/5/2009 11:29 PM
I really appreciate your work to this site.So thanks for it.

Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification: