Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The difference between a `global variable` and a `field`?

Fields are variables within a class or struct, local variables sit within a method and global variables are accessible in every scope (class and method included).

This makes me think that fields might be global variables but that global variables are not necessarily fields although I cannot think of a variable sitting outside of a class.

Is there a clear difference between the two?

like image 568
Arthur Mamou-Mani Avatar asked Oct 16 '12 11:10

Arthur Mamou-Mani


People also ask

What is the difference between variable and field?

In Java, all the variables must be declared before use. Field A data member of a class. Unless specified otherwise, a field can be public, static, not static and final.

What is the difference between a variable and a global variable?

Variables are classified into Global variables and Local variables based on their scope. The main difference between Global and local variables is that global variables can be accessed globally in the entire program, whereas local variables can be accessed only within the function or block in which they are defined.

What is difference between global and local variable?

Key Differences between Local Variable and Global Variable Local variables are created when the function has started execution and is lost when the function terminates, on the other hand, a Global variable is created as execution starts and is lost when the program ends.

What is difference between global and static variable?

A global variable can be accessed from anywhere inside the program while a static variable only has a block scope. So, the benefit of using a static variable as a global variable is that it can be accessed from anywhere inside the program since it is declared globally.


2 Answers

You tagged this C# and C# does not really have 'global variables'.

But a public static field (or property) would come close. The static makes it singular and gives it a 'global' lifetime.

like image 64
Henk Holterman Avatar answered Sep 20 '22 07:09

Henk Holterman


I think Wikipedia's definition is appropriate here:

In object-oriented programming, field (also called data member or member variable) is the data encapsulated within a class or object. In the case of a regular field (also called instance variable), for each instance of the object there is an instance variable: for example, an Employee class has a Name field and there is one distinct name per employee. A static field (also called class variable) is one variable, which is shared by all instances.

So a global variable is pretty much a static field (and therefore, a field).

like image 26
Kevin Gosse Avatar answered Sep 23 '22 07:09

Kevin Gosse