Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does the global:: stand for in C#

Tags:

c#

.net

What does the global:: stand for in C#? for example what is the difference between

private global::System.Int32 myInt;

and

private int myInt;

Thanks

like image 375
user1010572 Avatar asked Feb 25 '12 10:02

user1010572


2 Answers

It is the global namespace alias.

If you declare a type called System.Int32 in your codebase, you can distinguish the built in .NET one using this alias.

// your code
namespace System
{
  public class Int32
  {
  }
}

// You could reference the BCL System.Int32 like this:
global::System.Int32 bclInt;
System.Int32 myInt;

See How to: Use the Global Namespace Alias (C# Programming Guide) on MSDN.

like image 44
Oded Avatar answered Oct 15 '22 15:10

Oded


It's the "global" namespace - it forces the compiler to look for a name without taking other using directives into consideration. For example, suppose you had:

public class Bar{}

namespace Foo
{
    public class Bar {}

    public class Test
    {
        static void Main()
        {
            Bar bar1 = null; // Refers to Foo.Bar
            global::Bar bar2 = null; // Refers to the "top level" Bar
        }
    }
}

Basically it's a way of avoiding naming collisions - you're most likely to see it in tool-generated code, where the tool doesn't necessarily know all the other types in the system. It's rarer to need it in manually-written code.

See "How to: Use the global namespace alias" on MSDN for more details, along with the :: namespace qualifier.

like image 200
Jon Skeet Avatar answered Oct 15 '22 14:10

Jon Skeet