Thick_propheT
Thick_propheT

Reputation: 1060

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

Upvotes: 1

Views: 116

Answers (2)

p.s.w.g
p.s.w.g

Reputation: 149020

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:

Upvotes: 0

SLaks
SLaks

Reputation: 887413

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.

Upvotes: 1

Related Questions