I've created a class called Piece, which I used to create a 2D array in my main program.

This is the class:

namespace GG
{
    class Piece
    {
        public int rank;
        public int player;
    }
}

And is instantiated in my main program like so:

namespace GG
{
    public partial class frmPGame : Form
    {
        public frmPGame()
        {
            InitializeComponent();
        }

    Piece[,] board = new Piece[9, 8];
    mathFunction mFunc = newMathFunction();

    public void clear()
    {
        for (int y = 0; y < 8; y++)
            {
                for (int x = 0; x < 9; x++)
                {
                    board [x, y] = new Piece();
                    board [x, y].rank = -1;
                    board [x, y].player = 0;
                }
            }
    }

Now, I have ANOTHER class (named mathFunction) that does some math related work, and I would like to know if / how I can pass the array to it.

Do I instantiate "Piece" in the "mathFunction"? How do I pass the array and its contents from my main program to the "mathFunction"? And then how do I return it to main? Supposedly, I am to change some values in the 2D array.

Thanks in advanced.

Recommended Answers

All 5 Replies

You can pass it into constructor of the class and use it:

class Main
{
     Piece[,] board = new Piece[9, 8];
     private void GoToMath()
     {
          //code...
          MathFunction mf = new MathFunction(board); //pass data to other class
          board = mf.DoSomeWork();   //do some work there, and return data
     }   
}

class MathFunction
{
     Piece[,] board;
     class MathFunction(Piece[,] _board)
     {
           this.board = _board,
     }

     public Piece[,] DoSomeWork()
     {
          //do work...
          return this.board;
     }
}

Thanks. Do I have to repeat this:

private void GoToMath()
     {
          //code...
          MathFunction mf = new MathFunction(board); //pass data to other class
          board = mf.DoSomeWork();   //do some work there, and return data
     }

Everytime I need to call on that mf.DoSomeWork()? Are there any disadvantages to calling a new instance of the same thing (other than erasing whatever was in it)?

If you have to call a method on some othe class, you always have to use a reference of that class to get access to the public method (private are not visible at all).

Thanks. :)

You are welcome mate.
best regards,
bye

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.