C#: Passing objects to other forms?

Started by
2 comments, last by paulecoyote 18 years, 11 months ago
Say that you made a player object in Form1 : Form, and you open a new window in your application. How can the new window get your object by reference?
Advertisement
Getters/Setters?

The easiest way (at least as I remember) is using something called a "controller". A controller, should be a singleton pattern. IE: Something will only have 1 reference in the application.
ie:
class Singleton{   private static Singleton instance = new Singleton();   private MyObject object = null;   private Singleton()   {      if(instance == null)      {         object = new MyObject();      }   }   public static Singleton Instance   {      get { return instance; }   }      public MyObject GetMyObject   {      get { return object; }   }}   


From your Singleton class, you should be able access each object you create with the singleton. From those objects, you then access the methods of that class.

IE:
public class MyObject{   private String name;      public MyObject() {}      public String Name   {      set { if(value != null) name = value; }      get { return name; }   }}


And an example in practice
public class Form1 {   private Singleton instance = Singleton.Instance;   public Form1() {}   MyObject obj = instance.GetMyObject;   obj.Name = "John";}public class Form2{   private Singleton instance = Singleton.Instance;      TextField.Text = instance.GetMyObject.Name;}


HTH
Rooke
HTHRooke-----C makes it easy to shoot yourself in the foot; C++ makes it harder, but when you do, it blows away your whole leg. (Bjarne Stroustrup)
The key to this is seperating your user interface (form) from your business logic (rules of the game).

If your forms are just slaves to the game logic, or even better you split it up in to a model-view-controller type paradiagm where the view is completly seperated from the game, this kind of thing just becomes natural.

Try seperating out your concepts (like player, game, enemy, etc) in to seperate class files. Have a form called "GameView" and another called "PlayerView" and see where that kind of thinking leads you.
Anything posted is personal opinion which does not in anyway reflect or represent my employer. Any code and opinion is expressed “as is” and used at your own risk – it does not constitute a legal relationship of any kind.

This topic is closed to new replies.

Advertisement