XmlSerialization and Interfaces

I know that you cannot serialize / deserialize using the interface, but I am confused by the behavior that I see.

When I deserialize and get back to the interface, some properties are null. But if I go back to a specific type, does the same property matter?

So, given this XML (short for brevity):

<Page> <ComponentPresentations> <ComponentPresentation> <Component> <Categories> <Category> <Id>tcm:35-540-512</Id> 

Desamerization with

 var serializer = new XmlSerializer(typeof(Page)); page = (IPage)serializer.Deserialize(reader); page.ComponentPresentations[0].Component.Categories <-- is null 

But if I go back to type,

 var serializer = new XmlSerializer(typeof(Page)); page = (Page)serializer.Deserialize(reader); page.ComponentPresentations[0].Component.Categories <-- is not null! 

The page type provides an Interface Categories property and a property without an interface — I assume that I get around the problem of serializing the interface.

 public List<Category> Categories { get; set; } [XmlIgnore] IList<ICategory> IComponent.Categories { get { return Categories as IList<ICategory>; } } 

Is this because the interface property does not expose the setter?

0
source share
1 answer

Not. Problem Contravariance is not supported by List<T> and IList<T> . Here is a good reference.


Take a look at this simple code:

 public interface IMyInterface { } public class MyImplementation : IMyInterface { } List<MyImplementation> myImplementations = new List<MyImplementation>(); Console.WriteLine(myImplementations as IList<IMyInterface> == null); // OUTPUT: true!! 

So, as you can see, Categories as IList<ICategory> will always be null. So far Categories as IList<Category> will be fine.

Nothing to do with serialization .

+1
source

All Articles