Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global access vs. local variables

Tags:

c#

I have two objects that I will be mainly use inside of single class. I will initialize them at the beginning and use them throughout the life of the program. Now, my question is that if I should just create them as global variables and access them anywhere in the code (in side of single class) or I should create them as local variables and pass them as parameters to other functions. I just want to see what would be the best programming practice.

I am using C#.

Thanks.

like image 339
Tony Avatar asked Mar 24 '10 15:03

Tony


People also ask

Is it better to use local or global variables?

It all depends on the scope of the variable. If you feel that a certain variable will take multiple values by passing through various functions then use local variables and pass them in function calls. If you feel that a certain variable you need to use will have constant value, then declare it as a global variable.

What is the difference between global and local variables?

A global variable is a variable that is accessible globally. A local variable is one that is only accessible to the current scope, such as temporary variables used in a single function definition.

Are local or global variables faster?

The first is that allocating global variables may be faster, since they are only allocated once, at the time the program is first spawned, whereas local variables must be allocated every time a function is called.

Do global variables override local variables?

LOCAL variables are only accessible in the function itself. So, in layman's terms, the GLOBAL variable would supersede the LOCAL variable in your FIRST code above.


1 Answers

In general you should avoid global variables. If it will be practical, I recommend keeping them as locals and passing them as parameters to your functions.

As Josh pointed out, if these variables are only used inside a single instance of the class, then you should just make them private (or protected) members of that class and be done with it. Of course, then they could only be passed in as parameters to other methods with the same access level (IE, private).

Alternatively, you may consider using the Singleton Design Pattern, which is slightly cleaner (and preferable) to using globals.

like image 69
Justin Ethier Avatar answered Sep 20 '22 01:09

Justin Ethier