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 e.g.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With