Search code examples
c#classmultidimensional-arrayreferenceprogram-entry-point

How can I reference a 3D array from another class?


In the main program class I have:

 static void Main()
 {
    string[,,] anArray = new string [3,3,3];
        anArray[0,0,0] = "value1";
        anArray[0,0,1] = "value2"; .... //filling the rest of the array.
 }

How can I pass this array into another separate class "anotherClass" using a constructor with multiple arguments like:

 class AnotherClass
 {
 private string[,,] anotherClassArray;

 public string[,,] AnotherClassArray
 {
     get { return anotherClassArray;}
 }

 public AnotherClass (string[,,] fromAnArray)
 {
    anotherClassArray = new string [fromAnArray.Length];
 }
 }

I've seen examples with just a simple 1 dimensional array being passed from the Main program into another separate class and back again but when I tried following the same example for a multidimensional I get the error:

"Cannot implicitly convert type 'string[]' to 'string[,,*]'" when trying to initialize the new array.


Solution

  • If you want AnotherClass to have it's own separate, empty, instance of a 3D array, then you can do what Pikoh said. In this case, if you change the contents of the array, the original array created in Main is unaffected, and vice versa.

    If you want AnotherClass to reference the same array as the one created in Main, and therefor have access to it's same, filled in contents, then simply set the AnotherClass.anotherClassArray reference to equal fromAnArray in the AnotherClass constructor like so:

    public AnotherClass (string[,,] fromAnArray)
    {
       anotherClassArray = fromAnArray;
    }