views:

591

answers:

2

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.

A: 

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

JonnyD
It's not surprising that the same problem happens with VB.NET, since it's a .NET problem, not a C# problem.
John Saunders
+4  A: 

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();
}
Sterno
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!
Jack Lawson