9

I have an abstract class. Let's call it Lifeform. It looks something like:

public abstract class Lifeform {
    public virtual int Legs { get; set; }
    public virtual int Arms { get; set; }
    public virtual bool Alive { get; set; }
}

(The virtual attribute is due to the fact that I'm using nHibernate, which whines if they're not virtual properties.)

I then have a class which inherits from that Lifeform class; we'll call it Human. It looks something like:

public class Human: Lifeform {
    public virtual bool Hat { get; set; }
    public virtual int Age { get; set; }
    public virtual string Name { get; set; }
}

Everything's lovely, I can use my classes, Human gets the Legs, Arms, and Alive properties when I'm using it. Except, that is, when I attempt to make a web service using the Human class. The serialized object gives me Hat, Age, and Name - but no Legs, Arms, or Alive properties.

I've seen a workaround that suggests using

[System.Xml.Serialization.XmlInclude(typeof(Human))]

On the base class (Lifeform), but that seems like a horrible hack that violates OO. Putting links on the base class to the classes that inherit it? Eww.

Has anyone run into this specific issue before? Have any ideas? I'll provide more code if a more in-depth example would help describe what I'm doing more.

1
  • I had the same problem, and this helped me solve it. I ended up setting the attribute on the class instead of the method returning it, though.
    – Guffa
    Oct 19, 2009 at 19:06

2 Answers 2

9

From what I've read, you can include the XMLInclude attribute on the web method returning the object rather than in the base class. Still not pretty, but might appeal to you a little more than putting derived class names in the base class. I haven't tried it out, but I think you can do something like this.

[WebMethod]
[XmlInclude(typeof(LifeForm))]
public Human GetHuman()
{
   return new Human();
}
2
  • Awesome, thanks. At first it didn't work- but it seems to generate the correct code, it just doesn't display in the sample. I kept trying it and it didn't seem to work, until I figured "what the heck" and actually generated the serialized objects. Beautiful. Not perfect, but hey, it's way better than gunking up my base classes. Thanks! Aug 11, 2009 at 19:53
  • How about if you wanted to pass the base class as a parameter and cast it to Human in the GetHuman function? Possible? Jun 6, 2011 at 21:32
0

Ran into the exact same problem with VB.NET. Using the XMLInclude attribute, while ugly, did the trick.

1
  • It's not surprising that the same problem happens with VB.NET, since it's a .NET problem, not a C# problem. Aug 11, 2009 at 21:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.