Visual C# - Access instance of object created in one class in another

You'll need to declare the Soldier instance in in a higher scope.

One way of doing this would be to declare it inside Form1, then pass it to Form2, and so on.

public class Form1
{
    private Soldier tempSoldier = new Soldier();

    private void button1_Click(object sender, EventArgs e)
    {
        tempSoldier = new Soldier();
        tempSoldier.surname = textbox1.text;
    }

    private void GotoNextStep()
    {
        // pass the existing instance to the next form
        Form2 form2 = new Form2(tempSoldier);

        // display form 2 ...
    }
}

Another possibility is to use a singleton variable in a class that all the forms have access to.

public class MyAppManager
{
    private static readonly Soldier _soldier = new Solider();

    public static Soldier SoldierInstance
    {
        get { return _soldier; }
    }
}

private void button1_Click(object sender, EventArgs e)
{
    MyAppManager.SoldierInstnace.surname = textbox1.text;
}

The former approach is ok if there's a distinct sequence to the forms; the latter is better if difference forms could be used at different times or revisited.


You can also make Soldier a static variable :

public static Soldier soldier {get;set;}
private void button1_Click(object sender, EventArgs e)
{
    soldier = new Soldier();
    soldier.surname = textbox1.text;
}

Code in other forms:

Form1.soldier.name ="";

You should create a public property on your form that exposes the soldier. You can then access this property from the other forms.

// ...

public Soldier Soldier { get; private set; }

private void button1_Click(object sender, EventArgs e)
{
  Soldier tempSoldier = new Soldier();
  tempSoldier.surname = textbox1.Text;

  this.Soldier = tempSoldier;
}

// ...

Your Form2 class could look something like this:

public partial class Form2
{
  private Form1 form1;

  public Form2(Form1 form1)
  {
    this.form1 = form1;

    this.InitializeComponent();
  }

  public void DoStuffWithForm1()
  {
    // ...

    string surname = this.form1.Soldier.surname;

    // ...
  }
}