2

There is any way to convert/cast an int[][] array into an object[][] array?

int[][] = FillArray(); object[][] = iArray; 
9
  • 5
    Why would you want to do that? Performance will be affected considerably. Commented Sep 26, 2014 at 19:00
  • 2
    did you see my code? Commented Sep 26, 2014 at 19:00
  • 1
    You barely posted any code, lol Commented Sep 26, 2014 at 19:02
  • 1
    You might want to change over to using List<> instead. Easier to work with and convert. Commented Sep 26, 2014 at 19:03
  • 3
    @Shaharyar your title edit is invalid. Jagged arrays != multidimensional arrays. Commented Sep 26, 2014 at 19:08

3 Answers 3

5

If you don't want to use LINQ, you can use Array.ConvertAll.

int[][] iArray = FillArray(); object[][] oArray = Array.ConvertAll(iArray, x => Array.ConvertAll(x, y => (object) y)); 

The other answers with LINQ's Cast method are okay also.

But as I pointed out in comments, make sure you realize that you are boxing each value of the array. That can lead to performance problems if the array is of any considerable size.

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

5 Comments

Thank you for the code but the int[][] array is populate with random values.
@doro, those values are an example
That's was just an example. Call your FillArray method if you like. Edited.
-1 for not using the same random values he is using!
Well, the code compiled and seems to work. I am not sure for the result but this is smt else. Thank you! :-)
4

You can do:

object[][] objArray = iArray.Select(r => r.Cast<object>().ToArray()) .ToArray(); 

Comments

3

Some LINQ:

int[][] iArray = FillArray(); object[][] oArray = iArray.Select(i => i != null ? i.Cast<object>().ToArray() : null) .ToArray(); 

2 Comments

Why have a ternary operator? int can't be null, nor can a row.
@gunr2171 int can't be null, but int[] can.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.