Today I ran into an unexpected problem trying to serialize / deserialize a DataContract containing bool [,] DataMember. Neither csc nor runtime objected to this definition, but the values in the deserialized file bool [,] DataMember were incorrect. After reading this topic, my initial reaction was to convert the problematic property into an uneven array. Soon I had to abandon this approach, as this article reports that jagged arrays are executed with greed when accessed diagonally or randomly (exactly in my use case). Thus, I ended up writing a curatorial version of the solution proposed in the aforementioned msdn stream (converting a rectangle into a jagged one and vice versa) during export / import, see excerpts from the code below) and this works fine.
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 < d0; i++) { if (wrapper.Array[i].Length != d1) throw new ArgumentException("Not a rectangular array"); for (var j = 0; j < 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 < wrapper.Array.Length; i++) { wrapper.Array[i] = new bool[d1]; for (int j = 0; j < d1; j++) { wrapper.Array[i][j] = arr[i, j]; } } return wrapper; } return obj; }
I am interested, however, if there is a more concise solution to this or another approach.
source share