Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using directive to import subnamespaces

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?

like image 423
Miroslav Zadravec Avatar asked Jun 18 '26 09:06

Miroslav Zadravec


2 Answers

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.

like image 67
Reed Copsey Avatar answered Jun 19 '26 22:06

Reed Copsey


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;
like image 26
marcind Avatar answered Jun 19 '26 22:06

marcind



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!