Calanus
Calanus

Reputation: 26307

What does global:: mean in the .Net designer files?

Here is a question that I have had for some time but never actually got around to asking...

In quite a lot of the designer files that Visual Studio generates some of the variables are prefixed with global:: Can someone explain what this means, what this prefix does and where should I be using it?

Upvotes: 7

Views: 1612

Answers (4)

Ihar Voitka
Ihar Voitka

Reputation: 549

global:: namespace qualifier is used in auto generated to prevent collision in type resolving through nested namespaces.

Upvotes: 3

Rob Levine
Rob Levine

Reputation: 41328

The global namespace qualifier allows you to access a member in the global ("empty") namespace.

If you were to call an unqualified type (e.g. MyClass.DoSomething() rather than MyNamespace.MyClass.DoSomething()), then it is assumed to be in the current namespace. How then do you qualify the type to say it is in the global/empty namespace?

This code sample (console app) should illustrate its behaviour:

using System;

namespace MyNamespace
{
    public class Program
    {
        static void Main(string[] args)
        {
            MessageWriter.Write();          // writes "MyNamespace namespace"
            global::MessageWriter.Write();  // writes "Global namespace"
            Console.ReadLine();
        }
    }

    // This class is in the namespace "MyNamespace"
    public class MessageWriter
    {
        public static void Write()
        {
            Console.WriteLine("MyNamespace namespace");
        }
    }
}

// This class is in the global namespace (i.e. no specified namespace)
public class MessageWriter
{
    public static void Write()
    {
        Console.WriteLine("Global namespace");
    }
}

Upvotes: 12

Martin Liversage
Martin Liversage

Reputation: 106906

The prefix indicates the global namespace. Here is an example:

namespace Bar {
  class Gnat { }
}
namespace Foo {
  namespace Bar {
    class Gnat { }
  }
  class Gnus {
    Bar.Gnat a; // Foo.Bar.Gnat
    global::Bar.Gnat b; // Bar.Gnat
  }
}

Note how the member a perhaps inadvertedly refers to the Foo.Bar.Gnat class. To avoid this use the global:: prefix.

Upvotes: 4

Colin
Colin

Reputation: 10638

From here

When the left identifier is global, the search for the right identifier starts at the global namespace.

Upvotes: 1

Related Questions