Fin Warman
Fin Warman

Reputation: 43

C# - 2D Array of String Arrays

I am trying to create a world map for a console-based game.

In the World class I have string arrays that can be printed using a level print method.

public static string[] A1 = new string[]
{
    (" level data"),
    (" level data"),
};

This works if I do

Render.DrawLevel(World.A1);

where Render.DrawLevel takes args:

(string[] _level)

However, in the World Class, I want to create a two-dimensional array that can hold all of the Map's string arrays.

I have tried:

public static string[,][] Map = new string[,][]
{
    { A1 , A2 },
    { B1 , B2 },
};

But if I try to use:

World.Map[0,0]

as my arguments for level printed, I get given an error that this is NULL, instead of the string[] A1.

How can I create a 2d array of arrays, and refer to it properly for string[] arguments?

Thank you very much,

Fin.

EDIT: Incorrectly copied code as 'static void' not just 'static'.

Upvotes: 3

Views: 3926

Answers (3)

romanoza
romanoza

Reputation: 4862

Place the Map initialization after the initialization of the arrays. A1, A2, B1, B2 are equal to null during the initialization of Map.

The syntax is perfectly fine.

This works as intended:

    public static string[] A1 = new string[]
        {
            (" level data 1"),
            (" level data 2"),
        };

    public static string[] A2 = new string[]
        {
            (" level data 1"),
            (" level data 2"),
        };

    public static string[] B1 = new string[]
        {
            (" level data 1"),
            (" level data 2"),
        };

    public static string[] B2 = new string[]
        {
            (" level data 1"),
            (" level data 2"),
        };

    public static string[,][] Map = new string[,][]
    {
        { A1, A2 },
        { B1, B2 },
    };

Upvotes: 2

Peter Tsrunchev
Peter Tsrunchev

Reputation: 51

A two dimensional array is essentially an array of equally sized arrays. You can visualize it as a matrix, with each column (or row, doesn't really matter) as a separate array. So then the elements in the first row (column) would be the first elements of each of the arrays. What you are doing is trying to create a two dimensional array of arrays.

The best answer on this is a great read concerning your question.

Upvotes: 1

Ricky Keane
Ricky Keane

Reputation: 1700

Your signature for Map is incorrect, it can't be void and a multi-dimensional string array. Change it to:

    public static string[,][] Map = new string[,][]
        {
            {A1,A2 },
            {B1,B2 },
        };

Upvotes: 0

Related Questions