hi, i have just started to learn C#, my primary programming language has always been VB. I can't seem to figure out how to create a global variable used commonly among 2 forms. In VB i would just use a get set property, but it doesn't appear on the other form i would like to use it on and i do not know why. Any help would be much appreciated. Thanks.
Multiple forms and global variables C#
Collapse
X
-
Tags: None
-
Originally posted by xxsodapopxx5hi, i have just started to learn C#, my primary programming language has always been VB. I can't seem to figure out how to create a global variable used commonly among 2 forms. In VB i would just use a get set property, but it doesn't appear on the other form i would like to use it on and i do not know why. Any help would be much appreciated. Thanks.
If you are calling a method from another class (or form) and want to pass a value for this method to use you would need to create an instance of the second from on the first form, then call the method and pass it the required values.
FormName fn= new FormName()
fn.methodName(value )
You would need to declare the variable required as a parameter of that method.
methodName(int value)
{...}
Is that what you are meaning? -
.Net applications have a Property section that allows the tidy storage of user varriables. (Found in the solution explorer under Properties-> Settings)
Where you could set a string called "SomeVarria ble" to "this is my string"
And it can be accessed anywhere withen you code with:
Code:private static Properties.Settings mySettings = new Properties.Settings(); private void somefunction() { string somestring=mySettings.SomeVarriable; }
I ALSO (on the otherhand) like to keep a special class for my "global" varriables.
Code:public static class GlobalVars { public static int NumRetries=4; public static string baseDirectory="C:\\mydirec\\"; }
Code:private void somefunction() { string logdirec=GlobalVars.baseDirectory+"logs\\"; }
Comment
-
wow thank you both for your complete answers. They are going to be very helpful. I am going to be using the method based with the parameters.For this specific problem I am going to use the static property settings. Thank you.Comment
-
globals arn't the same in C# like in C or VB, but you can use properties to obtain the same result...
Add a new CS file to your project (not required but I think it helps keep track of the different classes and namespaces if you use one per file)
make some namespace and class; Their names don't matter the names this is just an example below
namespace userglobal
{class gloabalvars
{}
private static bool bIsSet=false; //monitor if the string has been set
private static string _myglobalstring ;
public static string myglobalstring
{}
get
{}
if(bIsSet)
{}
return _myglobalstring ;
else
{}
_myglobalstring = "Some default value";
return _myglobalstring ;
set
{}
_myglobalstring = value;
Comment
Comment