Be careful about nothing in managed code

Be careful about nothing in managed code

Here’s a pattern of code use I’ve seen in a few places. There’s a function DeserializeList that returns an array of various sizes, depending on the input. This code can be called to deserialize (rehydrate) an object from a stream. For example, an XML deserializer might create an XML node from a binary stream. The stream might indicate the number of XML Attributes or XML Child nodes as 0 (reader.Readint32 returns 0). When DeserializeList is called to get a list of the Attributes or Child nodes for an XML node, often that list is empty. The returned value is thus an array of length 0.

From inspection, the code already can return a NULL, so callers might already be written to handle the NULL return value. A simple fix is to return NULL if the count is 0.

One might think this is fine, and indeed, the code can be written so it functions correctly: creating an XML node with no attributes. However, the code is inefficient, and can slow down your application.