4

I'm trying to serialize an object and the following SerializationException is thrown:

Type 'System.Linq.Enumerable+d__71`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]' in Assembly 'System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is not marked as serializable.

Where is this object in my code? How would I find out? The object graph is fairly large.

Justin
  • 84,773
  • 49
  • 224
  • 367
Suraj
  • 35,905
  • 47
  • 139
  • 250
  • 1
    Its simply the stack for serialization...nothing about the object that can't be serialized – Suraj Mar 16 '11 at 03:41

3 Answers3

4

Try using Reflector and see if you can determine where the anonymous type d__71`1 is being used in your code.

Mark Hurd
  • 10,665
  • 10
  • 68
  • 101
  • 1
    thanks! I didn't even think to load my dll in reflector. Once I did it was easy to find d__71'1 and analyze its usage. Thanks! – Suraj Mar 16 '11 at 03:45
4

Sounds to me as though you've stored the results of calling an enumerator method without converting the result to a list.

When you have a method like this:

public IEnumerable<string> GetMyWidgetNames()
{
    foreach (var x in MyWidgets)
    { 
        yield return x.Name;
    }
}

The compiler turns this into a nested object with a name like the one you're seeing (one with a name you could never create yourself because of the embedded +)

If you then store a reference to this object inside something you try to serialise, you'll get the exception noted by the OP.

The "fix" is to ensure that your serialised objects always convert any IEnumerable<> assignments into lists. Instead of this

public IEnumerable<string> WidgetNames { get; set; }

you need to write:

public IEnumerable<string> WidgetNames
{
    get { return mWidgetNames; }
    set
    {
        if (value == null)
            mWidgetNames= null
        else mWidgetNames= value.ToList();
    }
}
private List<string> mWidgetNames;
Bevan
  • 43,618
  • 10
  • 81
  • 133
  • +1, System.Linq.Enumerable... means this set of data is returned from a Linq query. Though it implements IEnumerable, it is not serializable. Usually you need to call ToList() or ToArray() on this Linq result, and then it can be serialized. – Lex Li Mar 16 '11 at 03:43
  • this helped a lot. I wish SO let me split answer. Your answer along with @Mark Hurd's helped me track down the problem. It was in fact an IEnumerable that had been concatenated and needed to flatten into a list. I flipped a coin for whom to award the answer. – Suraj Mar 16 '11 at 03:44
-1

Try to serialize an object (single type) at a time and see when it blows up. You can do this manually, or through reflection.

RQDQ
  • 15,461
  • 2
  • 32
  • 59
  • So - why the downvote? This is exactly how I would solve the problem (and I have a pretty good feeling it would work). – RQDQ Mar 16 '11 at 12:14