netserializer
netserializer copied to clipboard
Supporting IEnumerable<T>
In the current design of NetSerializer, would it be difficult to support properties of type IEnumerable<T>
so that a consumer could populate with the standard List<T> or array of T? Right now I'm getting a KeyNotFoundException
when I try to serializer an object with an IEnumerable<T>
property, where the value of that property is set to a List<T>
.
note that it does seem to work if I register the List<T>
, but its a bit of an awkward use-case because I have to know my IEnumerable<T>
implementations ahead-of-time
That is a drawback with the NetSerializer design. You have to register all the types that will be serialized when initializing NetSerializer, and both the serializer and deserializer sides have to have the exact same types.
That design is partly the reason why NetSerializer is fast and simple.
makes sense. In the particular case of IEnumerable<T>, would you consider auto-registering Array<T> and List<T> since it's such a common use case? Completely understand if not.
You could, of course, create a custom serializer for IEnumerable<T>, and in that custom serializer send details about the type etc. But I recommend using some other serializer instead of NetSerializer if you start doing something like that =).
NetSerializer is a very specialized serializer, not a generic one. It has limitations.
Well, that would create extra (de)serializer entries to be created. With the v4, the actual (de)serialization code is created only when used the first time, so... Maybe that would not be too much extra. But then, I don't like the idea very much that NetSerializer guesses what types the user may serialize later. That's a bit against the "minimal" design.
However, I wonder if it would be possible make it easier for the user to add those types. A callback, perhaps, where the user could return list of additional types. Hmm, I don't know...
So if I understood right, you have objects with fields likeIEnumerable<int>
, and those may contain List<int>
values?
I can see the dilemma and it's good to keep to the "minimal" principal. In my case it's a property, not a field, but yes I have something like:
public IEnumerable<int> Ids { get; private set; }
If the setter is called with a List<int>
then serialization won't work unless List<int>
is added.
I don't prefer the callback approach - it still puts the burden on the caller. What I love about NetSerializer is that it works "out-of-the-box" with a [Serializable] attribute and to the extent that you are doing "simple" things like using primitives. Although IEnumerable is an interface, it's so ubiquitously used and ubiquitously backed by a List or an Array, that I consider this scenario in the set of "vanilla/simple" objects models. I think this should either be handled by NetSerializer as an exception to the no-interface rule as a convenience OR the user should just register it to keep with the existing principals.