Function and usage of global keyword in C

  • 2021-09-20 21:18:37
  • OfStack

global is a new keyword in C # 2.0, and in theory, if the code is written well, it doesn't need to be used at all.

Suppose you now write a class called System. Then when you write System in your code, the compiler doesn't know whether you want to refer to the System class you wrote or the System namespace of the system, and the System namespace is already the root namespace and can no longer be specified by completely limiting the name. In previous versions of C #, this was a problem that could not be solved. Now, you can use global:: System to represent the System root namespace, and use your own MyNamespace. System to represent your own class.

Of course, this should not happen. You should not write a class named System.

Code demo:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace globalFunc
{
    class Program
    {
        static void Main(string[] args)
        {
            System sys = new System();
            global::System.Console.WriteLine("global.");
            global::System.Console.ReadKey();
        }
    }
    public class System { }
}

Although using has an System namespace, there is also an public class System {...} class below. In this case, if you use System. Console. WriteLine directly, you will report an error, because the nearest System class will be found, so there is no Console in this System class. Therefore, if you need to use it, you need to use global:: System. Console. WriteLine like the above 1, because classes with global tags will be searched globally, and my understanding is that System classes will be searched gradually from the outermost to the inside.


Related articles: