0

i want to write this code( java ) on c# , but receive this error message

Unable to cast object of type 'System.SByte[,]' to type 'System.SByte[][]'.

java code is :

byte[][] bArr2 = (byte[][]) Array.newInstance(byte.class, new int[]{2, 8});

my csharp code is

sbyte[][] bArr2 = (sbyte[][])Array.CreateInstance(typeof(sbyte), new int[] { 2, 8 });

thanks

  • See https://stackoverflow.com/questions/4648914/why-we-have-both-jagged-array-and-multidimensional-array – Sweeper Dec 25 '19 at 00:30

1 Answers1

2

You already know the dimensions. So you should just declare the array normally.

Java:

byte[][] bArr2 = new byte[2][8];

C#:

sbyte[,] bArr2 = new sbyte[2,8];

In general, when porting between languages, I recommend to keep the standard language docs open so you can learn about the basic syntax like this (sbyte[,]).

AndrewF
  • 1,827
  • 13
  • 25
  • ` byte[] bArr3 = new byte[8]; bArr2[1] = bArr3; ` – user1462548 Dec 25 '19 at 00:59
  • if use [,] array , how to bArr3 into bArr2[1] ? i dont understand it , – user1462548 Dec 25 '19 at 01:02
  • See answers to [Multidimensional Array \[\]\[\] vs \[,\]](https://stackoverflow.com/a/12567378/666583). You would need to make a jagged array if you want to work with individual sub-arrays like that. But making that change, you would no longer be working with a strongly-typed 2-D array, i.e., you would lose some type safety. Are you sure you need `bArr3` at all? Instead, you should be able to work with the elements of `bArr2` directly. Java does not have this feature. – AndrewF Mar 25 '21 at 23:34