arichexe
asked on
C# global variables
How do I define global variables, ones that can be modified by multiple functions within a class?
ASKER
It's within the class, so how would I define a class object?
public class MyClass {
string variableone;
string variabletwo;
public void MyFunction() {
}
}
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
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!"
}
}
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!
ASKER
Jaynus, I'm getting "An object reference is required for the nonstatic field, method, or property MyNameSpace.MyClass.MyCoun t." What's causing this?
class MyClass {
int MyCount = 0;
public static void Main() {
MyCount = MyCount + 1
MySubroutine()
}
public static void MySubroutine() {
ConsoleWriteLine(MyCount);
}
}
class MyClass {
int MyCount = 0;
public static void Main() {
MyCount = MyCount + 1
MySubroutine()
}
public static void MySubroutine() {
ConsoleWriteLine(MyCount);
}
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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.