Often when including namespaces or assemblies into my code, I often run into strange cases where a namespace is inherited from another, yet classes from the parent namespace are not available. For example, when using List<>
or Dictionary<>
, I use the System.Collections.Generic
namespace. However, if I also want to use an IEnumerator
, I also have to include the System.Collections
namespace. Shouldn't System.Collections
already be referenced by any member of System.Collections.Generic
, as it is a child? Both namespaces also share the same assembly, mscorlib.dll.
Why is the parent namespace not included when the child is?
Shouldn't System.Collections already be referenced by any member of System.Collections.Generic, as it is a child?
No. There's no inheritance between namespaces. A using
directive only imports types from that namespace - it doesn't import types from namespaces starting with the given namespace, or namespaces included within the given namespace's name.
For example, after:
using System.Collections;
... that doesn't let you use List<T>
as a simple name for System.Collections.Generic.List<T>
, nor does it let you use Guid
as a simple name for System.Guid
.
The only exception to this is that if you're writing code within a namespace declaration of X.Y.Z
, that implicitly imports namespaces X.Y
and X
(as well as X.Y.Z
, of course). (In that example, X.Y
is the enclosing namespace if X.Y.Z
, but it's not an inheritance relationship.)
See more on this question at Stackoverflow