I've searched forum for similar issues and as I understand, global variables is to be avoided. For me that is not logical yet, as I'm new to programming. If I've understood all this correctly, a static variable should do the job that I'm looking for.
I've made a combobox of four choices in the mainwindow and when a comboboxitem is selected, variable b is declared. This is done in a private void SelectionChanged.
When the comboboxitem declaring variable b is selected, a usercontrol pops up. I want to use variable b further in my program, but I can't access it. I've tried to declare static int b;
in the beginning of the code, but I'm not sure if I understand the use of a static variable correctly. Can someone please help me?
It is possible to create a variable for global use. Just create static field or property:
And wherever you want, you can just set or get values from that storage:
Avoid global variables and
static
keyword at all unless you 100% sure there is no other address your solution (sometimes you might be forced to use statics typically with legacy code hot fixes).So suggestion:
you can do this insted
And later access it like
To create a "global variable", it should be public and static, and declared in a public static class. In .NET it's a common way to declare constants (e.g. Math.PI), but they're not variables!
non-public variables are only visible in classes or methods where they're declared.
ps: using global variables is very bad.