Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the usage of global:: keyword in C#?

Tags:

syntax

c#

keyword

What is the usage of global:: keyword in C#? When must we use this keyword?

like image 707
masoud ramezani Avatar asked Feb 26 '10 08:02

masoud ramezani


People also ask

What is global keyword in C?

The C language does not have a global keyword. However, variables declared outside a function have "file scope," meaning they are visible within the file. Variables declared with file scope are visible between their declaration and the end of the compilation unit ( .

What is the use of global variable in C?

Use of the Global Variable in C The global variables get defined outside any function- usually at the very top of a program. After this, the variables hold their actual values throughout the lifetime of that program, and one can access them inside any function that gets defined for that program.

What is the correct use of global keyword?

A global keyword is a keyword that allows a user to modify a variable outside of the current scope. It is used to create global variables in python from a non-global scope i.e inside a function. Global keyword is used inside a function only when we want to do assignments or when we want to change a variable.

What is global declaration in C?

The C compiler recognizes a variable as global, as opposed to local, because its declaration is located outside the scope of any of the functions making up the program. Of course, a global variable can only be used in an executable statement after it has been declared.


1 Answers

Technically, global is not a keyword: it's a so-called "contextual keyword". These have special meaning only in a limited program context and can be used as identifiers outside that context.

global can and should be used whenever there's ambiguity or whenever a member is hidden. From here:

class TestApp {     // Define a new class called 'System' to cause problems.     public class System { }      // Define a constant called 'Console' to cause more problems.     const int Console = 7;     const int number = 66;      static void Main()     {         // Error  Accesses TestApp.Console         Console.WriteLine(number);         // Error either         System.Console.WriteLine(number);         // This, however, is fine         global::System.Console.WriteLine(number);     } } 

Note, however, that global doesn't work when no namespace is specified for the type:

// See: no namespace here public static class System {     public static void Main()     {         // "System" doesn't have a namespace, so this         // will refer to this class!         global::System.Console.WriteLine("Hello, world!");     } } 
like image 166
Anton Gogolev Avatar answered Oct 05 '22 01:10

Anton Gogolev