Zachary Louie
Zachary Louie

Reputation: 49

C# setting the values of a multidimensional array with a constructor

I would like to know how to use a class constructor to set the values of a multidimensional array. I have used a constructor to set the values of integers before (see below), but this syntax doesn't seem to work with arrays.

Here is how I would use a constructor with integers

public class Warehouse
{   
    //declares instance variables
    public int radios;
    public int televisions;
    public int computers;


    //Creates constructor with 0 inventory
    public Warehouse()
    {
        radios = 0;
        televisions = 0;
        computers = 0;
    }

This code above has worked for me in previous assignments. However, the code below is what I am currently attempting to fix. Visual Studio says that the variables are unused and will remain at the default value. Also, the commas in the lines assigning a value to each index are underlined red saying that a semicolon was expected instead. Is there another way of using a constructor to set the values of these arrays? I would just declare the values along with the arrays, but the assignment asks for a constructor to be used.

public class Matrix
{
    public double[,] matrixX;
    public double[,] matrixY;
    public double[,] xySum;
    public double[,] xyDiff;
    public double[,] xScalar;

    public Matrix()
    {
        matrixX = { { 1.1, 2.2, 3.3 }, { 4.4, 5.5, 6.6 }, { 7.7, 8.8, 9.9 } };
        matrixY = { { 9.9, 8.8, 7.7 }, { 6.6, 5.5, 4.4 }, { 3.3, 2.2, 1.1 } };
        xySum = { { 0.0, 0.0, 0.0 }, { 0.0, 0.0, 0.0 }, { 0.0, 0.0, 0.0 } };
        xyDiff = { { 0.0, 0.0, 0.0 }, { 0.0, 0.0, 0.0 }, { 0.0, 0.0, 0.0 } };
        xScalar = { { 0.0, 0.0, 0.0 }, { 0.0, 0.0, 0.0 }, { 0.0, 0.0, 0.0 } };
    }

Upvotes: 0

Views: 1643

Answers (1)

John Wu
John Wu

Reputation: 52240

Whenever instantiating a new object, the new keyword has to appear somewhere, always (unless you are using Reflection and Activator.CreateInstance()). So to initialize the arrays, you have to declare the new double[,] as part of the assignment.

So instead of this:

    matrixX = { { 1.1, 2.2, 3.3 }, { 4.4, 5.5, 6.6 }, { 7.7, 8.8, 9.9 } };

Use this:

    matrixX = new double[,] { { 1.1, 2.2, 3.3 }, { 4.4, 5.5, 6.6 }, { 7.7, 8.8, 9.9 } };

Upvotes: 1

Related Questions