Sunday, February 07, 2010

Serializing a Null

What do you suppose happens when you pass a null reference to XmlSerializer.Serialize as the object to be serialized?

You'd probably think an error, or perhaps that nothing would be written to the stream to which the object is to be serialized. Instead, you get something like this, depending on what the type is that you initialized the serializer with (I used a List<string>):

<ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xsi:nil="true" />

In other words, you get an empty fragment, an element with xsi:nil="true", an empty (in this case) list.

Passing a non-null but empty List<string> gave me this fragment:

<ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" />

So that xsi:nil is very important: it's the difference between an object with no elements and an object that is itself null.

I would not have guessed you could serialize a null, but you can.

0 Comments:

Post a Comment

Links to this post:

Create a Link

<< Home