Global object

In a particular app, an object is instantiated as from a frameset form1 pops up for collecting data that user enters to fill in some of the object's properties. Upon clicking a button, form 2 pops up for user to enter more data and fill in more properties of the object. This scenario continues with additional forms in a common frameset... At the end, after going thru several forms as described above, the app will use the object's properties to add, update or delete data in a database. How can such a global object be declared and implemented to be shared across forms
Thanks much.


Answer this question

Global object

  • Brian Ph

    use a singleton class:

    public class GlobalObject {

    private static GlobalObject _instance;
    public static GlobalObject Instance {
    get{
    if(_instance == null) _instance = new GlobalObject();
    return _instance;
    }


    private int _one;
    private bool _two;
    private string _three;

    public int One {
    get{return _one;}
    set{_one = value;}
    }
    public bool Two {
    get{return _two;}
    set{_two = value;}
    }
    public string Three {
    get{return _three;}
    set{_three = value;}
    }

    private GlobalObject() {
    lock(this) {
    _one = -1;
    _two = true;
    _three = "something";
    }
    }

    }



    then in each class, you simply create in instance of this object:


    class 1:

    GlobalObject a = GlobalObject.Instance;



    class 2:

    GlobalObject b = GlobalObject.Instance;



    class 3:

    GlobalObject c = GlobalObject.Instance;





    a b and c will all have the same instance of GlobalObject. so any can change the values:

    class 1:
    a.One = 23;

    class 2 will have:

    int globalOne = b.One; // will == 23

    and so on.

  • knarf

    My current question is especially how to pass an object  from a particular form onto the next form after updating it. Please kindly provide sample code or site links about passing an object around forms thru their constructors. 
    Thanks much.

  • stan catalin

    best way would be to either use a static variable, or you can pass this object around to the constructor of your forms
  • Global object