Friday, October 21, 2005

IList<T> Won't XmlSerialize!

So as long as we're talking about XmlSerializer bugs, let me point out a really, really bad one: if your type has members of type IList<T>, it won't serialize! Aagh! What's worse is that Microsoft has decided not to fix this bug until after 2.0. Crap!

 

OK, I can sort of understand that not everyone uses XmlSerializer directly as their XML API of choice (as I do). So maybe if people like me were the only customers who would be affected by this problem they'd be justified in saying "we'll fix it later". But I'm not: XmlSerializer is used by the ASP.NET web services infrastructure. So if you were thinking of using IList<T> properties from your web service parameter types…forget it. Won't work. Guaranteed to be busted in v2.0.

 

Of course, it's not the end of the world. Generated collection classes (I use CodeSmith) have been an option for typesafe collections since v1.0. But generics were supposed to free us from those, not just give us a slightly more efficient way to implement them.

 

This bug has me pretty annoyed right now, but maybe I'm just moving my way through The Circle of (Software) Life.

 

Update: OK, this isn't quite as bad as I thought. It turns out that List<T> will serialize just fine. However, FxCop complains about List<T>, and if you've ever tried to use FxCop, you know that dealing with exclusions is often more trouble than it's worth. Fortunately, the FxCop violation that got triggered suggested using either Collection<T>, ReadOnlyCollection<T>, or KeyedCollection<T> instead. As you know, I've already worked a bit with KeyedCollection<T>…suddenly System.Collections.ObjectModel seems even cooler.

 

Anyway, once I switched over to using Collection<T> (the appropriate choice in this case) everything serializes correctly. Woohoo! I'd be happier with support for IList<T>, but I can totally live with this.

 

I hope you don't mind my constant updates. I was going to be embarrassed about having to constantly correct myself, but then I remembered that this blog is nothing if not a public record of the fact that I still haven't managed to learn everything there is to know. :)

4 comments:

  1. Good info to know. Thanks for sharing.

    ReplyDelete
  2. Allow me to do the stupid question: Just why is Collection<T> acceptable to FxCop while List<T> not? What's better about the former?

    ReplyDelete
  3. Tomas, probably because they want you to derive from Collection<T> to expose your strongly-typed collection classes in public APIs rather than using List<T>. At least, that was the recommendation in the Framework Design Guidelines book.

    ReplyDelete
  4. I just got caught by the "IList<> won't serialize" problem, so it does mean it's a good thing you keep this post updated! Thanks!

    ReplyDelete