Search code examples
c#instances

C# - Sharing information between instances


My code is quite simple. When I click a button in the first class it creates two instances of Master and one instance of Arena. Arena needs to receive information from both Master instances and Arena needs to send information to each Master instances, but the information is not the same for both Master instances.

//When I press a button...
master = new Master(ip1.Text);
master.Show();

slave = new Master(ip2.Text);
slave.Show();

arena = new Arena(master,slave);
arena.Show();

ARENA CLASS:

private Master master;
private Master slave;

public Arena(Master master,Master slave)
{
    InitializeComponent();
    this.master = master;
    this.slave = slave;

}

My question is:

I can create new Arena(master,slave) because the instances master and slave are created before. But I need to use something like:

master = new Master(ip1.Text,arena);
master.Show();

slave = new Master(ip2.Text,arena);
slave.Show();

arena = new Arena(master,slave);
arena.Show();

But I cant do this because when master and slave instances are created, arena = null. FIXED!!

EDIT:

I have a instance called Arena that receives the instances Master and Slave as an argument.

    private Master master;
    private Master slave;

    public Arena(Master master,Master slave)
    {
        InitializeComponent();
        this.master = master;
        this.slave = slave;

    }

My question is how can I return different values for master and slave. For example:

public int missao_enviada;


 private void btn_enviar_Click(object sender, EventArgs e)
 {
missao_enviada = 1;
 }

   public int enviou_missao()
    {
        return missao_enviada;
    }

But I only want to return missao_enviada to Master master instance and not Master slave instance.

Is there a way to do this?


Solution

  • You should assign Arena to Master And Slave in Arena's constructor method

    private Master master;
    private Master slave;
    
    public Arena(Master master,Master slave)
    {
        InitializeComponent();
        this.master = master;
        this.slave = slave;
    
        master.Arena = this;
        slave.Arena = this;
    }
    

    You should modify your Master class and add Arena property to it

    public class Master
    {
        public Arena Arena { set; get;}
    }