Just sharing some of my inconsequential lunch conversations with you... RSS  

Wednesday, August 06, 2008

Serializing problem

Well, not exactly a problem, more like an annoyance... a friend of mine was having some trouble deserializing a DTO from a web service he was consuming. The problem seemed to be related with an array of int being represented as an atribute. We reversed the web service assembly (yeap, we didn't have the sources but we it resided on the same server) and found the probable source of the problem:

myDTO.MyIntAsArray = new int[0];

Uhm, though not as I'd prefer, still clearly legal, right? The problem is how .NET handles this. On serialization, it doesn't seem to check it against null, and on deserialization it just throws an exception. Here's a sample:

        public class MyDTO
public int[] MyCountlessIntArrayAsAttribute;

public int[] MyCountlessIntArrayAsElement;

public int[] MyNullArrayAsElementAsAtribute;

public int[] MyNullArrayAsElementAsElement;

public MyDTO HelloWorld()
MyDTO myDTO = new MyDTO();

myDTO.MyCountlessIntArrayAsAttribute = new int[0];
myDTO.MyCountlessIntArrayAsElement = new int[0];
myDTO.MyNullArrayAsElementAsAtribute = null; // just re-stating the obvious
myDTO.MyNullArrayAsElementAsElement = null; // just re-stating the obvious

return myDTO;

With this representation, here's what gets serialized:

<?xml version="1.0" encoding="utf-8" ?> 
- <MyDTO MyCountlessIntArrayAsAttribute="">
<MyCountlessIntArrayAsElement />

I won't argue of the fact that an array of 0 elements is not probably what we should use here, neither if an element is the best way to represent this array of int. One thing seems clear here, this is a .NET bug, and it remains since .NET 1.1 till .NET 3.5. So beware of int[] attribute representations :)



No comments:

Development Catharsis :: Copyright 2006 Mário Romano