Link to home
Start Free TrialLog in
Avatar of arichexe
arichexe

asked on

C# global variables

How do I define global variables, ones that can be modified by multiple functions within a class?
Avatar of jaynus
jaynus

Do you mean multiple classes within an assembly? If its within the class, just define a class object..if you want it within teh assembly...declare static variables/methods inside a class

e.g.

internal class MyStaticStuff {
     public static string MyStaticString = "blah!";
     public static XmlDocument MyStaticObject = new XmlDocument();

     public static string MyStaticFunction(string Heh) {
          return(Heh);
     }
}

Make sense? The static attribute creates instances of the properties/methods upon runtime, rather than requiring an instance of the object.
Avatar of arichexe

ASKER

It's within the class, so how would I define a class object?
public class MyClass {
     string variableone;
     string variabletwo;

     public void MyFunction() {

     }
}
BAH!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

Never use global variables! use properties instead! People! what happened to your oop manners? =o)


public class whatever

OOPS!!!

public class whatever
{
        private string privateVar;

        public whatever(){privateVar = "yahoo!";} //constructor

        public string Blah //notice different case
        {
               get
               {
                      return blah;
                }
               set
               {
                      blah = value;
               }
         }
}
               

public class AnotherObject
{
          public AnotherObject(){} //constructor
         
          private string GetBlahFromWhatever()
          {
                whatever obj = new whatever()
                return obj.Blah; //returns "yahoo!"
          }
}
oops, it should be private string blah not private string privateVar... damn I can't think today!
Jaynus, I'm getting "An object reference is required for the nonstatic field, method, or property MyNameSpace.MyClass.MyCount."  What's causing this?

class MyClass {
     int MyCount = 0;

     public static void Main() {
        MyCount = MyCount + 1
        MySubroutine()
     }

     public static void MySubroutine() {
        ConsoleWriteLine(MyCount);
    }
}
ASKER CERTIFIED SOLUTION
Avatar of jonvaughan
jonvaughan

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial