Fixed statement and null input...

I'd like some input on a change we're considering for Whidbey.

Consider the following wrapper class:

 unsafe class Wrapper
{
    public void ManagedFunc(byte[] data)
    {
        fixed (byte* pData = data)
        {
            UnmanagedFunc(pData);
        }
    }
    void UnmanagedFunc(byte* pData)
   
    }
}

In this class, I've fixed a byte[] array so I can pass it to an unmanaged method. I've included “UnmanagedFunc()“ in my program to illustrate what it looks like, but I would normally be calling a C function through P/Invoke in this scenario.

The problem with this code is that some C APIs accept null values as arguments. It would be nice to be able to pass a null byte[] and have that translate to a null pointer, but the fixed statement throws if it gets a null array.

There's an obvious workaround:

  public void ManagedFuncOption1(byte[] data)
 {
     if (data == null)
     {
         UnmanagedFunc(null);
     }
     else
     {
         fixed (byte* pData = data)
         {
             UnmanagedFunc(pData);
         }
     }
 }

and a less obvious one.

 public void ManagedFuncOption2(byte[] data)
{
    bool nullData = data == null;
    fixed (byte* pTemp = nullData ? new byte[1] : data)
    {
        byte* pData = nullData ? null : pTemp;
        UnmanagedFunc(pData);
    }
}

Thr problem with the workarounds is that they are ugly, and they get fairly complicated if there is more than one parameter involved.

The language spec (section 18.6) says that the behavior of fixed is implementation defined if the array expression is null, so we could change our behavior so that fixing a null array would result in a null pointer rather than an exception. 

Questions:

  1. Have you written code where this would be useful?
  2. Are there situations where the change of behavior would cause you problems?
  3. Are the workarounds simple enough that this isn't an issue?