DataContractSerializer not supporting rectangular Arrays
<p>I ran into an unexpected problem today, attempting to serialize/deserialize a DataContract containing a bool[,] DataMember. Neither csc nor runtime objected this definition, however the values in the deserialized bool[,] DataMember just weren't correct. After reading <a href="http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/96d99982-bace-4c3e-93cb-7c9ca905f317/" rel="nofollow">this thread</a>, my initial reaction was to convert the problematic property into a jagged array. I had to abandon that approach soon however since <a href="http://msdn.microsoft.com/en-us/magazine/cc163995.aspx" rel="nofollow">this article</a> informs that jagged arrays perform miserably when accessed diagonally or randomly (exactly my use case). So I ended up writing a curated version of the solution proposed in the above msdn thread (convert rectangular to jagged and visa versa upon export/import, see code excerpts below) and that works fine.</p>

<pre><code>public object GetDeserializedObject(object obj, Type targetType)
{
    if (obj is GridArrayWrapper)
    {
        bool[,] arr;
        GridArrayWrapper wrapper = (GridArrayWrapper)obj;
        if (wrapper.Array == null) return null;
        int d0 = wrapper.Array.Length;
        if (d0 == 0)
        {
            return new bool[0, 0];
        }
        var d1 = wrapper.Array[0].Length;
        arr = new bool[d0, d1];
        for (int i = 0; i &lt; d0; i++)
        {
            if (wrapper.Array[i].Length != d1) throw new ArgumentException("Not a rectangular array");
            for (var j = 0; j &lt; d1; j++)
            {
                arr[i, j] = wrapper.Array[i][j];
            }
        }
        return arr;
    }
    return obj;
}

public object GetObjectToSerialize(object obj, Type targetType)
{
    if (obj is bool[,])
    {
        bool[,] arr = (bool[,])obj;
        GridArrayWrapper wrapper = new GridArrayWrapper();
        int d0 = arr.GetLength(0);
        int d1 = arr.GetLength(1);
        wrapper.Array = new bool[d0][];
        for (int i = 0; i &lt; wrapper.Array.Length; i++)
        {
            wrapper.Array[i] = new bool[d1];
            for (int j = 0; j &lt; d1; j++)
            {
                wrapper.Array[i][j] = arr[i, j];
            }
        }
        return wrapper;
    }
    return obj;
}
</code></pre>

<p>I'm wondering however if there is a more concise solution to this or another approach.</p>
