If I import a namespace like this:
using System;
Why can't I access subnamespace IO like this:
IO.FileInfo fi;
Insted I must write either a whole path:
System.IO.FileInfo fi;
Or import whole IO namespace and use class without namespace
using System.IO;
FileInfo fi;
Am I missing something here?
While it's often convenient to think in terms of "namespaces" and "sub-namespaces", in reality, there are only type names.
In this case, there is a single type:
System.IO.FileInfo
The using directive allows the compiler to add
System.
to any type to see if it finds a matching type name. However, this won't findIO.FileInfo
, as it will be looking for aIO
type, containing aFileInfo
nested type.The way the language is designed may seem more cumbersome, but it eliminates the confusion of nested type names vs. namespace names, since it only looks for types within the namespaces defined in the using directives. This reduces the chance of type naming collisions.