using directive to import subnamespaces

1k views Asked by At

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?

3

There are 3 answers

0
Reed Copsey On BEST ANSWER

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 find IO.FileInfo, as it will be looking for a IO type, containing a FileInfo 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.

0
marcind On

C# does not really have the concept of subnamespaces. The periods in the namespace name are just there for logical organization purposes.

System and System.IO are two different namespaces as far as C# is concerned.

If you just need the FileInfo class you could do this:

using FileInfo = System.IO.FileInfo;
0
Max Toro On

What you are trying to do only works if the context type is in the same namespace hierarchy, e.g.:

namespace System {
  class MyClass {
    IO.FileInfo fi;
  }
}

You can also have relative imports, like this:

namespace System {
  using IO;
}