3

I have an object that is of type Array (that is object.GetType().IsArray returns true). My question is how can I find out whether it is a jagged or a multidimensional array? Is there a way to serialize the array so that the code "doesn't know" the difference (using reflection)?

Note that the array is of arbitrary length/dimension. I was thinking that I could perhaps parse the Type.Name to search for [, (as in one part of [,,]) or [][] to distinguish between these -- but that still means I'll have two code paths for each case and I feel like there should be a better way to accomplish this than parsing type names.

For a jagged array, it seems easy enough to take the array and then keep indexing it using [] to iterate over all the elements, however, this approach does not work for multidimensional arrays.

3
  • you are writing a custom serialization mechanism? why not use one of the several options that are built into the .net framework? Commented May 10, 2013 at 5:33
  • It's mostly a learning exercise :) Commented May 10, 2013 at 5:35
  • Try to look into the customization options of DataContractSerializer Commented May 10, 2013 at 8:11

1 Answer 1

2

A jagged array is an array of arrays. So all you have to do is look at the element type and check that it is an array as well:

 static bool IsJaggedArray(object obj) { var t = obj.GetType(); return t.IsArray && t.GetElementType().IsArray; } static void Test() { var a1 = new int[42]; Debug.Assert(!IsJaggedArray(a1)); var a2 = new int[4, 2]; Debug.Assert(!IsJaggedArray(a2)); var a3 = new int[42][]; Debug.Assert(IsJaggedArray(a3)); } 

Cast to Array and use the Rank property to find the number of dimensions for a multi-dimensional array.

Sign up to request clarification or add additional context in comments.

1 Comment

I figured out I can also use Array.Rank to determine if an array is multidimensional (for which Rank > 1 is true). This works great, thank you!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.