Question

This is what I'm looking to do:

public class NormalClass
{
    [XmlAttribute]
    public int Example;
}

[XmlRoot]
public class GenericClass<T> where T : HasXmlElementAttribute
{
    [XmlArray]
    public List<T> Variables;
}

I thought where T : IXmlSerializable might work, but it did not.

Is this even possible to do? If so, what is the proper way?

Additional Thoughts/Edit

Is there a way to achieve this same goal? Is there a way to only allow classes that can be xml serialized?

Thanks

Was it helpful?

Solution 2

No, you cannot use generic type constraints to limit the type parameters by what attributes they are decorated with. You can only use generic type constraints to limit type parameters by:

  • What base the type parameter inherits
  • What interfaces the type parameter implements
  • What constructors the type parameter provides
  • Whether the type parameter is a value type or a reference type

Further Reading:

OTHER TIPS

Attributes are not part of the type system.

You cannot constrain a type parameter based on the presence of an attribute.


Side note: This justification is not quite valid; constructors aren't part of the type system either, yet : new() is a valid constraint.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top