简体   繁体   中英

A C# class with a null namespace

While going through some legacy code I discovered that you can declare a C# class without placing it in a namespace (in this scenario I have an ASP.NET WebForms application and some of the web forms are not declared within any namespace).

A GetType() on such a class returns a type where the namespace property is set to null .

I did not know that this was allowed - can anyone suggest why it would be desirable to have a class that is not declared within a namespace?

It certainly isn't great practice. It does makes some examples easier, like "hello world" - maybe the C# designers were going for code-golf ;p

But yes, it is an oddity. I'm not aware of any resounding reason that we need to be able to directly use the global namespace. Even for extension methods I'd rather add a using directive to bring them in...

Interestingly - there seem to be 40-odd such in mscorlib.dll and 20-odd in system.dll

var mscorlib = typeof(string).Assembly.GetTypes()
   .Where(t => string.IsNullOrEmpty(t.Namespace)).ToList();
var system = typeof(Uri).Assembly.GetTypes()
   .Where(t => string.IsNullOrEmpty(t.Namespace)).ToList();

(but all private / compiler-generated)

Perhaps to allow interoperability with languages that do not support namespaces.

Update

After a little spelunking I can see a case that MS use.

All .Net Framework assemblies have some standard classes in the global namespace eg

  • FXAssembly: version info.
  • ThisAssembly: assembly info.
  • AssemblyRef: dependent assembly info.

These classes contain canned meta-data which would otherwise be more difficult\\expensive to get at. I'm guessing that they chose to locate these in the global namespace so that it would be a standard\\conventional location where tools\\utilities\\etc could get at them. This information is bootstrapping\\meta information so logically sits above the concept of namespaces.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM