Artyom
Artyom

Reputation: 3571

Why a tuple doesn't have parameterless constructor while `[Serializable]`?

System.Tuple(T1,..) classes marked with [SerializableAttribute] (see msdn). But they don't have a parameterless constructor so not serializable by XmlSerializer as it was cleared before at here. So why not add one?

Upvotes: 4

Views: 1442

Answers (1)

Thomas Levesque
Thomas Levesque

Reputation: 292615

You don't need a type to have the [Serializable] attribute to serialize it with XmlSerializer, and the fact that a type has the attribute doesn't mean you can serialize it with XmlSerializer; the two are unrelated. [Serializable] is only used for binary serialization (*) (which doesn't need a parameterless constructor).

To sum it up:

  • Binary serialization
    • requires the [Serializable] attribute
    • doesn't require a public parameterless constructor
  • XML serialization
    • doesn't require the [Serializable] attribute
    • requires a public parameterless constructor

So you can't serialize a Tuple<...> using XmlSerializer.


Regardless of the above, Tuple<...> could have a default constructor, but it wouldn't make much sense: tuples are immutable (you can't set their properties), so if you created an instance with the default constructor, the properties would always have their default values and couldn't be changed. (also, the fact that the properties are read-only is also something that prevents tuples from being serialized with XmlSerializer, which only supports public read-write properties)


(*) actually, not just binary serialization, but any serialization formatter (e.g. BinaryFormatter, SoapFormatter...)

Upvotes: 4

Related Questions