jamiet
jamiet

Reputation: 12264

Generic class constraints - can I specify that the Generic type can be serialized as XML?

I am writing a Generic class that attempts to serialize an object of Type T as XML. Unfortunately (as I'm sure you know) not all objects can successfully be serialized as XML hence I would like to be able to write a constraint that specifies T can only be a class that is XML Serializable. Is this at all possible?

Pretty sure the answer to this is "no" but figured I would ask anyway in case there's something I have missed.

Upvotes: 2

Views: 654

Answers (2)

Marc Gravell
Marc Gravell

Reputation: 1062770

The only constraints available are:

  • class / struct
  • new()
  • BaseType / Interface

Of these, the only 2 that are slightly interesting are :new() (since XmlSerializer demands a public parameterless constructor) and :Interface (since IXmlSerializable is one of the options); however:

  • IXmlSerializable is not required, so that doesn't apply
  • no constraint here forces the type to be a public type (and a public type of a public type, in the case of nested types)
  • it doesn't account for the generics limitations

so in short: no, this isn't something you can enforce via generic constraints

Upvotes: 5

driis
driis

Reputation: 164291

You're right, the answer is no, you cannot constrain generic types to be XML serializable.

The reason for this, is that the XML Serializer has some very specific rules about what it will serialize (most notable, it serializes public properties only, and only types that have a public parameterless constructor). The factors that make a class XML serializable cannot be expressed in terms of types, and therefore there is no way to make a generic constraint for it.

You can constrain to an interface, so perhaps a solution would be to use a marker interface on your types that are XML serializable. Then again, this doesn't work if you don't control the types you want to serialize.

Upvotes: 4

Related Questions