I'm trying to generate code from an XSD that has two complexTypes extending a common complexType. The inheritors have a common property named "value", which has different types. Of course I can't put it on my base type due to XSD rules. My intention is to polymorphically call the property on the base type which would invoke the right method on the subclass. Is this possible?
Here is my XSD
<xs:complexType name="Property">
<xs:attribute name="name" type="xs:string" use="required"/>
</xs:complexType>
<xs:complexType name="StringProperty">
<xs:complexContent>
<xs:extension base="Property">
<xs:attribute name="value" type="xs:string" use="required"/>
</xs:extension>
</xs:complexContent>
</xs:complexType>
<xs:complexType name="BooleanProperty">
<xs:complexContent>
<xs:extension base="Property">
<xs:attribute name="value" type="xs:boolean" use="required"/>
</xs:extension>
</xs:complexContent>
</xs:complexType>
This generates the following code:
public partial class Property {
private string nameField;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string name {
get {
return this.nameField;
}
set {
this.nameField = value;
}
}
}
public partial class StringProperty : Property {
private string valueField;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string value {
get {
return this.valueField;
}
set {
this.valueField = value;
}
}
}
public partial class BoolProperty : Property {
private bool valueField;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public bool value {
get {
return this.valueField;
}
set {
this.valueField = value;
}
}
}
And here's what I want to do:
// ConfigProperties is an array of Property objects
foreach (Property property in config.ConfigProperties)
{
// Doesn't compile since Property.value doesn't exist in the base class.
Console.WriteLine(property.value);
}
I tried implementing a "value" getter property on the Property object hoping the subclasses' "value" property definitions would hide it, but that doesn't do the trick:
public partial class Property
{
public virtual string value
{
get { throw new NotImplementedException(); } // this method is called instead of the Property subclass methods
}
}
FOLLOW-UP QUESTION EDIT: The answers confirm my fears that this is not possible. Would it still be possible though to do the following in some manner:
foreach (Property property in config.ConfigProperties)
{
somevalue = property.GetValue();
}
where GetValue() is a method that figures out what return type it should have by virtue of the subclass of Property it actually is using? Pardon me for being extremely lazy. I'm given to believe that it's a virtue. =)