Thomas Thomas - 1 year ago 77
C# Question

Are Hashtables Serializable?

I see a pervasive belief (2009 article) throughout the internet that the

class is not serializable; however, I cannot find any modern documentation that supports this notion.

The belief stems from another ill-documented belief that the
interface prevents serialization; however, I cannot find anything in MSDN that supports this claim, today.

and contains extension methods that accept serialization information.

So, what's the deal? Is
serializable? Where is the documentation that supports this notion surrounding

Further Clarification (please read):

The statement that
is not serializable is supported by plenty of documentation; however, this focuses on the use of XML-based serialization interactions with a class.
as mentioned both in the comments, below, and through MSDN indicates that a class is serializable. It also means the class the must be responsible for its own serialization.

I think this negates the statement that a Hashtable is not serializable. That is perhaps the genesis of my question.

Answer Source

The pervasive belief is so pervasive because it's true:

var t = new Hashtable();
t.Add("Hi!", "I'm here");
t.Add("Hm", "Yup");

var serializer = new XmlSerializer(typeof(Hashtable));

using (var sw = new StringWriter())
  serializer.Serialize(sw, t);



NotSupportedException: The type System.Collections.Hashtable is not supported because it implements IDictionary.

That doesn't mean that it's literally impossible to serialize a hash table. Of course I can just iterate over all the keys and values, write them to a string and then reconstruct the hashtable from that. It's just that I can't use the serialization infrastructure fully.

What's the reasoning here? It's actually quite simple - XmlSerializer is designed to produce good XML, in the spirit of the interchange format XML was designed to be. And XML doesn't have any kind of dictionary or "key-value" mechanism that would fit. So to support hashtable serialization, they'd have to make their own "sub-format" with its own rules. And back when .NET was being designed, this was a huge no-no - XML was an interchange format. Any extension (hah) to the format means you're no longer compatible, no matter how good of an idea you have.

Of course, nowadays, everyone and their grandmother are producing XML data that isn't used for interchange purposes. And it's not entirely a bad thing (after all, .NET config files are also a XML format). But it's also kind of wrong.

In contrast, take something like BinaryFormatter. That's a class where the .NET team designed the whole format, and isn't limited by a standard. And lo and behold - BinaryFormatter can serialize and deserialize a Hashtable just fine.

So the slightly more correct belief would be "Hashtable cannot be serialized to valid standard XML. The XmlSerializer class in particular will throw an error when you attempt to serialize a Hashtable."