PDA

Click to See Complete Forum and Search --> : Globals


carstenht
Jan 7th, 2007, 07:12 AM
Hi

Since global variables arent availible in C#, what can I use to access variables inside other classes etc.

Fx, I want to access the variable testStr created in button 1 from button 2:


private void button1_Click(object sender, EventArgs e)
{

String testStr = "Hello World";
}

private void button2_Click(object sender, EventArgs e)
{
MessageBox.Show(testStr);

}

jmcilhinney
Jan 7th, 2007, 08:37 AM
You don't need a global variable for that. The simple fact is that all variables only exist inside the block in which they're declared. Your 'testStr' variable is declared inside the button1_Click method so it only exists inside that method. If you want to be able to access the same variable from multiple methods then you need to declare it at the class level, i.e. inside the class but outside any method.

A global variable is considered to be one that is visible throughout the project. The way to create a global variable in C# is to declare it as friend static within some class. The friend part makes it accessible throughout the project but not outside, while the static part makes it accessible without creating an instance of the class. Variables of this nature should be avoided if it is reasonably possible.

carstenht
Jan 7th, 2007, 09:07 AM
Yeah, but I had an Object Oriented Programming course at university a year back, which used Java as example language, and I believe there where some way to access those elements, but this may not work for C# it seems.

carstenht
Jan 7th, 2007, 09:15 AM
Making the varibles public, should solve it according to what i have read, but I get a strange error....:

public int x = 2;

Error:
Error 1 Invalid expression term 'public' E:\Documents and Settings\carsten\My Documents\Visual Studio 2005\Projects\fileio\fileio\Form1.cs 30 13 fileio

Error 2 ; expected E:\Documents and Settings\carsten\My Documents\Visual Studio 2005\Projects\fileio\fileio\Form1.cs 30 20 fileio

jmcilhinney
Jan 7th, 2007, 05:43 PM
You cannot declare local variables public or any other access level. As I said, local variables exist within the method in which they are declared only. If you declare the variable at the class level, i.e. outside any method definition, then you get to choose its access level, e.g. public, private, etc. Regardless of the access level you specify, a class-level variable is accessible throughout the class in which it is declared. If you declare it public then it is also accessible outside the class, but that doesn't make it a global variable. A public member variable still requires an instance of the class to be created and each instance has its own value for that variable. I've already told you how to create a genuine global variable.

Also, it is considered poor form in most situations to expose variables publicly. In most cases you should declare a private variable and expose it via a public property.