What is the global keyword in CSharp?
During the Christmas break, I received the following question:
What does C# global:: actually do? Code example, from table adapter code:
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "2.0.0.0")] [global::System.Serializable()] [global::System.ComponentModel.DesignerCategoryAttribute("code")] [global::System.ComponentModel.ToolboxItem(true)] [global::System.Xml.Serialization.XmlSchemaProviderAttribute("GetTypedDataSetSchema")] [global::System.Xml.Serialization.XmlRootAttribute("AutoTwitDataSet")] [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.DataSet")] public partial class AutoTwitDataSet : global::System.Data.DataSet {
The global:: specifier tells the compiler to start looking for the namespace or class starting from the root. You’ll see it in system-generated code so that the code always works. That way if you have a namespace right under your current namespace that is the same as the top level namespace the code is trying to access, there won’t be a conflict.
For example, say you have namespace A and namespace B and namespace B.A if I write code in namespace B.A that needs to reference a class in namespace A, without global:: I have no way of getting to it. If I reference A.classname, the compiler will look for classname in B.A. With global:: I can tell it to look for classname in global::A.classname and it will find classname in the proper location.
This keyword snuck in during version 2.0. Since most of us don’t need it, most of us don’t even know it exists. I didn’t until this past weekend.
Other post in Advanced CSharp
- Two Interfaces. Same Method. Two meanings. - September 29th, 2008
- Making values nullable - October 9th, 2008
- CSharp's Property Shortcuts - October 23rd, 2008
- Readonly variables in CSharp? Really?! - October 29th, 2008
- Dispose with Using - November 10th, 2008
- Delegates in .NET - December 4th, 2008
- Using Sealed in CSharp - December 8th, 2008
- CSharp checked and unchecked - December 11th, 2008
- Advanced CSharp - unsafe mode - December 15th, 2008
- Volatile variables and CSharp threads - December 22nd, 2008
- What is the global keyword in CSharp? - December 29th, 2008
- CSharp fixed keyword - January 5th, 2009
- using - There's more there than you are using - February 2nd, 2009
- Stackalloc in CSharp - February 16th, 2009
- Removing Warnings from CSharp Compile Cycle - March 10th, 2009
- && vs & and | vs ||... What's the difference? - March 16th, 2009
- Advanced CSharp - yield - March 25th, 2009
- Just say “No!” to C# Regions? Really?! - April 16th, 2009
- C# “” better than string.Empty? - April 20th, 2009
- .Net String Pool – Not Just For The Compiler - April 22nd, 2009
- CSharp ?? Operator - May 18th, 2009
- Using VB.NET From CSharp - July 1st, 2009
If you're new here, you may want to subscribe to my RSS feed. Thanks for visiting!











