Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A C# class with a null namespace

Tags:

namespaces

c#

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?

like image 850
Richard Ev Avatar asked Jan 05 '11 10:01

Richard Ev


2 Answers

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)

like image 103
Marc Gravell Avatar answered Sep 20 '22 16:09

Marc Gravell


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.

  • 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.

like image 39
Tim Lloyd Avatar answered Sep 22 '22 16:09

Tim Lloyd