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.
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.