4
var t = new List<byte?[,]>();
var t2 = new byte?[4, 4][];

var r = new List<byte?[,]>(t);
var r2 = new List<byte?[,]>(t2); // error

I thought C# lists and arrays are both Enumerable, and that lists can be constructed from an enumerable object to create a copy of the collection.

Whats wrong with the last line from the example above?

Compile error: The best overloaded method match for 'List.List(IEnumerable)' has some invalid arguments.

alan2here
  • 3,223
  • 6
  • 37
  • 62

2 Answers2

3

If t2 should be an array of 2D arrays (list assignment suggests so) then the declaration of t2 is wrong. If think you are after:

var t = new List<int[,]>();
var t2 = new int[10][,];
for (int i = 0; i < t2.Length; ++i)
{
    t2[i] = new int[4, 4];
}

var r = new List<int[,]>(t);
var r2 = new List<int[,]>(t2); // no error!
gwiazdorrr
  • 6,181
  • 2
  • 27
  • 36
  • It might be nice if you also reference the blog post from Eric Lippert on "Arrays of Arrays" that Ani posted in the comments. – Jonathon Reinhart Jul 27 '12 at 16:51
  • 2
    I haven't really used it as a reference since this is quite obvious, but for future reference: http://blogs.msdn.com/b/ericlippert/archive/2009/08/17/arrays-of-arrays.aspx – gwiazdorrr Jul 27 '12 at 17:02
  • It's not that obvious, the article opens with the idea that most people would slip up in the same way I did. – alan2here Jul 27 '12 at 17:05
0

Whats wrong with the last line from the example above?

The line throws error because t2 is new byte?[4, 4] a array of 2d array, well as r2 is a List of byte?[,] 2d array

var r2 = new List<byte?[,]>(t2); // error

so solution will be do pass a list of byte?[,] in it like this

var r2 = new List<byte?[,]>(new List<byte?[,]>());

Also t is the matching 2d array in a list that can be passed in r2

var r2 = new List<byte?[,]>(t);
HatSoft
  • 11,077
  • 3
  • 28
  • 43
  • 2
    t is a (list) of ((2d array) of (byte?)). t2 is an (array) of ((2d array) of (byte?)). – alan2here Jul 27 '12 at 16:40
  • @alan2here yes your right did not notice the [] at the end. I was in a hurry to post answer first. thank you ill correct my answer now – HatSoft Jul 27 '12 at 16:42
  • 1
    @alan2here See the question comments. You are incorrect. `t2` is a (2d array) of (array of (byte?)). And that's why the conversion to `IEnumerable` fails. – Jonathon Reinhart Jul 27 '12 at 16:47
  • Ahh, thanks. It does seem to compile now. I've possibly been reading the line the wrong way round. – alan2here Jul 27 '12 at 16:52
  • @alan2here I don't understand why I got -1 for I gave the solution to it – HatSoft Jul 27 '12 at 16:53