Serializing .NET dictionary [duplicate]

Which serialization API?

For example, DataContractSerializer can handle dictionaries, especially with the (optional) [CollectionDataContract] markup. protobuf-net will handle them (below). Others may not…

    var data = new Dictionary<string, int>();
    data.Add("abc", 123);
    data.Add("def", 456);

    var clone = Serializer.DeepClone(data);

As will BinaryFormatter:

    using (MemoryStream ms = new MemoryStream())
        var bf = new BinaryFormatter();
        bf.Serialize(ms, data);
        ms.Position = 0;
        clone = (Dictionary<string, int>) bf.Deserialize(ms);

Leave a Comment