Where is this non-serializable object?

I am 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 the 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 do I know? The graph of the object is quite large.

+4
source share
3 answers

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

+4
source

It seems to me that you saved the results of calling the enumerator method without converting the result to a list.

If 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 similar to the one you see (with a name that you can never create because of the built-in + )

If you then keep the reference to this object inside of what you are trying to serialize, you will get the exception indicated by the OP.

Fix β€” Make sure your serialized objects always convert any IEnumerable <> lists to 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; 
+4
source

Try to serialize the object (one type) at a time and see when it explodes. You can do this manually or through reflection.

-1
source

Source: https://habr.com/ru/post/1343868/


All Articles