• You are here: 
  • Home
  • How to return an array - null or empty?

How to return an array - null or empty?

Posted on April 8th, 2005

I was writing some code today and had a few methods that were returning arrays of values.  I was wondering what the guidelines were about the proper way to return an array from an API so I did a quick search and turned up the following:
String and Array properties should never return a null reference. Null can be difficult to understand in this context. The general rule is that null, empty string (”"), and empty (0 item) arrays should be treated the same way. Return an empty array instead of a null reference.” — from http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpgenref/html/cpconarrayusageguidelines.asp
This makes a lot of sense and takes the burden off the developer of having to check for null in the returned value before doing something as simple as checking its length.

Filed under .NET |

2 Responses to “How to return an array - null or empty?”

  1. Wesner Moise Says:
    April 8th, 2005 at 9:12 pm

    See my post on http://wesnerm.blogs.com/net_undocumented/2004/02/empty_arrays.html

    why Empty Arrays are preferred and need not result in additional memory usage (since empty arrays are immutable and thus sharable).

  2. Griffin Caprio Says:
    April 8th, 2005 at 9:37 pm

    Removing the burden from the developer in the case of nulls is the basis of the Null Object pattern:

    http://c2.com/cgi/wiki?NullObject

    It comes is very handy.

Leave a Reply