C # class with empty namespace

While running through some legacy code, I found that you can declare a C # class without placing it in a namespace (in this case I have an ASP.NET WebForms application, and some web forms are not declared in any namespace).

A GetType() in such a class returns a type in which the namespace property is null .

I did not know that this is allowed - can anyone suggest why it is desirable to have a class that is not declared in the namespace?

+7
source share
2 answers

This, of course, is not a good practice. This makes a few examples simpler, like "hello world" - perhaps C # designers were going for code golf, p

But yes, this is weird. I do not know of any high-profile reason why we need to be able to directly use the global namespace. Even for extension methods, I would rather add a using directive to bring them to ...

Interestingly, in mscorlib.dll are apparently 40 such odd 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 / compilers)

+5
source

Perhaps to ensure compatibility with languages ​​that do not support namespaces.

Update

After a little spelunking, I see a case that uses MS.

All .Net Framework assemblies have some standard classes in the global namespace, for example.

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

These classes contain canned metadata that would otherwise be more difficult / expensive. I assume that they decided to find them in the global namespace so that it was a standard \ normal place where the tools \ utilities \ etc could get on them. This information is boot \ meta-information, therefore logically sits above the concept of namespaces.

+3
source

All Articles