Search code examples
c#genericsxml-serializationwhere-clausetype-constraints

C# use where keyword on classes with XmlElementAttribute properties


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


Solution

  • 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: