Skip to content

Default collections

Kyle McClellan edited this page Sep 7, 2022 · 3 revisions

As of 0.4, MessagePack for CLI supports 'Default Abstract Collections'. It means that if you use well known abstract collections, MessagePack for CLI built-in (and auto generated) serializers recognize them, handle them correctly. This means you can write following class declaration now:

public class Foo
{
    // Although IList<T> is abstract type (interface), you can specify it.
    public IList<int> Integers { get; set; }
}

How to Handle Default Abstract Collections

Serializer library, namely SerializationContext recognizes default abstract collection types and their default implementations, so it simply returns serializers for default implementation classes instead of throwing exception.

What are Default Abstract Collections

'Default collections' refers well known abstract collection types in BCL. Namely, following abstract types are considered as default collection:

Abstract Default Collection Type Default Implementation Type Note
`System.Collections.Generic.IEnumerable<T>` `System.Collections.Generic.List<T>`  
`System.Collections.Generic.ICollection<T>` `System.Collections.Generic.List<T>`  
`System.Collections.Generic.IList<T>` `System.Collections.Generic.List<T>`  
`System.Collections.Generic.IDictionary<TKey,TValue>` `System.Collections.Dictionary<TKey,TValue>`
`System.Collections.IEnumerable` System.Collections.Generic.List<MsgPack.MessagePackObject>`  
`System.Collections.ICollection` `System.Collections.List<MsgPack.MessagePackObject>`  
`System.Collections.IList` `System.Collections.List<MsgPack.MessagePackObject>`  
`System.Collections.IDictionary` `MsgPack.MessagePackObjectDictionary`  
`System.Collections.Generic.ISet<T>` `System.Collections.Generic.HashSet<T>` .NET 4.0 and greater.
`System.Collections.Generic.IReadOnlyCollection<T>` `System.Collections.Generic.List<T>` .NET 4.5 and greater
`System.Collections.Generic.IReadOnlyList<T>` `System.Collections.Generic.List<T>` .NET 4.5 and greater
`System.Collections.Generic.IReadOnlyDictionary<TKey,TValue>` `System.Collections.Generic.Dictionary<TKey,TValue>` .NET 4.5 and greater

Overriding Default Implementation Classes

You can override default implementation classes by overriding default collcetion types as following:

var context = new SerializationContext();
// You can override all closed generic types by specifying generic type definition.
context.DefaultCollectionTypes.Register( typeof( IList<> ), typeof( Collection<> ) );

// You also able to override specific closed generic type by specifying closed generic type.
// For following example, other closed types including IList<string> etc. are not affected.
context.DefaultCollectionTypes.Register( typeof( IList<int> ), typeof( Collection<int> ) );