Virus721
Virus721

Reputation: 8315

C# - 3D array of 3D arrays

I want to have a very large 3D grid. If I simply create a 3D array (i.e T[,,]) I'm going to end up having a lot of unused (3D) positions in that grid, and due to memory usage, the grid will be far from how large I need it to be.

So my I idea is to make a "hollow" 3D grid of sub 3D grids (aka chunks) where each position contains a sub 3D grid. For chunks that are empty, the 3D array of that chunk does not exist in the parent 3D grid.

So I have a value of type : T[,,][,,]

Where the "top level" grid that contains the chunks is going to be a 3D array whose positions contain references to the chunks, or null if the chunk is empty.

My question is : how do I even initialize a value of type T[,,][,,] ? If I do new T[3,3,3][3,3,3] for example, the compiler is yelling :

CS0178  Invalid rank specifier: expected ',' or ']'

Thank you.

Upvotes: 1

Views: 736

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726549

The syntax for creating a new array is as follows:

T[,,][,,] a = new T[3,3,3][,,];

This gives you a 3D array of null values. You can set them to non-null 3D arrays as needed:

a[1,2,2] = new T[8,8,8];

You may consider other alternatives for storing "chunks" of your 3D grid - for example, you could make a Dictionary with three-element tuples as keys and 3D arrays as values. This Q&A describes other available alternatives for implementing 3D matrices in C#.

Upvotes: 4

Related Questions