Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serializing .NET dictionary [duplicate]

Tags:

c#

Possible Duplicate:
Serialize Class containing Dictionary member

Can I serialize a Dictionary?

like image 789
softwarematter Avatar asked Aug 19 '09 10:08

softwarematter


People also ask

Can you have duplicates in a Dictionary C#?

[C#] Dictionary with duplicate keys The Key value of a Dictionary is unique and doesn't let you add a duplicate key entry.

Can Dictionary be serialized?

Dictionary can't be serialized as a document.

Is .NET Dictionary serializable?

The serialization and deserialization of . NET objects is made easy by using the various serializer classes that it provides. But serialization of a Dictionary object is not that easy. For this, you have to create a special Dictionary class which is able to serialize itself.

What is serializing in C#?

Serialization is the process of converting an object into a stream of bytes to store the object or transmit it to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization.


1 Answers

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);
    Console.WriteLine(clone["abc"]);
    Console.WriteLine(clone["def"]);

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);
    }
like image 122
Marc Gravell Avatar answered Sep 17 '22 14:09

Marc Gravell