tags:

views:

103

answers:

3

A little help understanding this keyword from the .Net experts please.

Here is what raised the question for me:

alt text

+1  A: 

It's a namespace, not a keyword.

Mitch Wheat
@Mitch, So why would I use it? Resharper is telling me it's not needed, but Microsoft's code generation uses it. I'm trying to understand where I would ever use it. Thanks
Paul Fryer
@Paul: do not edit generated code. Not even in ReSharper. Generated code is a lot like sausage - you don't want to know what's in there.
John Saunders
@John, I'm not editing generated code, just trying to understand what it's doing. I have some code generation processes I'm working on, so I'd like to understand what others are doing any why.
Paul Fryer
Would the downvoter please leave a comment. Thanks.
Mitch Wheat
+6  A: 

The keyword global:: causes the compiler to bind names starting in the global namespace as opposed to in the current context. It's needed in places where a bindable member exists in a given context that has the same name as a global one and the global one is desired.

For example

class Test {
  class System {}
  public void Example() {
    System.Console.WriteLine("here"); // Error since System binds to Test.System
    global::System.Console.WriteLine("here"); // Works
}

The corresponding MSDN page has a few more examples (including the one above)

JaredPar
+7  A: 

It is best to use the global namespace prefix in generated code. This is done to avoid situations where a similar named type exists in your namespace.

If you create a type named System.Diagnostics.DebuggerNonUserCodeAttribute inside your namespace you will notice that ReSharper no longer says that the global:: is not needed. The code generator simply wants to avoid any collisions with the names of your own types.

Martin Liversage
@Martin, Very helpful, thank you.
Paul Fryer