views:

79

answers:

2

Taking this article on classes and structs as an example:

http://msdn.microsoft.com/en-us/library/ms173109.aspx

namespace ProgrammingGuide
{
    // Class definition.
    public class MyCustomClass
    {
        // Class members:
        // Property.
        public int Number { get; set; }

        // Method.
        public int Multiply(int num)
        {
            return num * Number;
        }

        // Instance Constructor.
        public MyCustomClass()
        {
            Number = 0;
        }
    }
    // Another class definition. This one contains
    // the Main method, the entry point for the program.
    class Program
    {
        static void Main(string[] args)
        {
            // Create an object of type MyCustomClass.
            MyCustomClass myClass = new MyCustomClass();

            // Set the value of a public property.
            myClass.Number = 27;

            // Call a public method.
            int result = myClass.Multiply(4);
        }
    }
}

suppose I wanted to make use of the "myClass" defined in the Main routine elsewhere in the program as if it were a global class.

How would I do that?

+1  A: 
static MyCustomClass myClass;
public static MyCustomClass MyClass {get {return myClass;}}
static void Main(string[] args)
{
    // Create an object of type MyCustomClass.
    myClass = new MyCustomClass();

    ...
}

Now you can use Program.MyClass

Marc Gravell
Alternatively, look at the singleton pattern: www.pobox.com/~skeet/csharp/singleton.html
Marc Gravell
A: 

Something like the example below.

class Program
{
    public MyCustomClass myClass;

    public Program()
    {
        // Create an object of type MyCustomClass.
        myClass = new MyCustomClass();

        // Set the value of a public property.
        myClass.Number = 27;

        // Call a public method.
        int result = myClass.Multiply(4);
    }

    static void Main(string[] args)
    {
        Program program = new Program();
    }
}
Spencer Ruport