Thursday, April 23, 2009

Be Coded or Be Cast Out - a XMLInclude and Casting issue


When you don't have access to the code of a class in a webservice and you inherit from that class, you can't use xmlinclude. The reason is you need to put the XMLInclude attribute on the base class.

So when I pass my derived class to the webmethod, it complains.

Fine no worries. I will cast it to the base class type and that should work, right? Wrong!

Objects are reference types and the variable that you are assinging the cast to, even if it's defined as the base class, in pointing to the derived class has the type of the derived class. Even though you can only access the properties and methods of the base class at design time (makes sense since this object is declared as the base class type). Why is this? It's because it's a reference type.

You don't believe me. Run your code in debug mode and mouse over the variable that was assigned the cast object (base class type). Reflection will show you it's the derived class, even though you just casted it to a base class.

What does this mean? You can't use XMLInclude and you can't cast the derived class object to work with the webservice method.


You need to create a new instance of the base class object and copy all the properities manually (in code) from the derived class object. I put this in a method (e.g. BaseClass DerivedClass.ToBaseClass())

I wish there was a better way. If you have access to the base class and it can see the derived class definition. All you have to do is use XMLInclude to include the derived class type.

See XmlInclude - Not Quite as Useless as I Thought

No comments: