interlocking namespaces

  • Thread starter Thread starter Abdessamad Belangour
  • Start date Start date
A

Abdessamad Belangour

Hi,
The namespace property of Type class returns the namespace of a given type.
is there any function to test that a namespace is nested within an other
namespace ?
Thanks in advance.
 
Abdessamad,

Not really. In order to do that, you will have to do some string
comparison on your own. It shouldn't be hard though, given that namespaces
are period-delimited.

Hope this helps.
 
In most of the CLR, namespaces are fiction, and the name of the type
actually includes the namespace (some .NET languages don't understand
namespaces). Looking specifically at the Type class, the Namespace property
returns the entire type name (including the C# namespace), minus the (C#)
name of the type, so given:

namespace f.o.o.b.a.r
{
public class X { }
}

which is the same thing as:

namespace f
{
namespace o
{
namespace o
{
namespace b
{
namespace a
{
namespace r
{
public class X { }
}
}
}
}
}
}

When referring to typeof(X), the Namespace property will return:
"f.o.o.b.a.r"
 
If you got a class like this

namespace MyOuterNamespace
{
namespace MyInnerNamespace
{
class MyClass
{
}
}
}

then the Type.Namespace property returns the string
"MyOuterNamespace.MyInnerNamespace". Using this (and some string
manipulation) you should be able to "parse" out which namespace(s) the
type/class is nested within.

Petter
 
-------------------
From: "Petter" <[email protected]>
Newsgroups: microsoft.public.dotnet.languages.csharp

If you got a class like this

namespace MyOuterNamespace
{
namespace MyInnerNamespace
{
class MyClass
{
}
}
}

then the Type.Namespace property returns the string
"MyOuterNamespace.MyInnerNamespace". Using this (and some string
manipulation) you should be able to "parse" out which namespace(s) the
type/class is nested within.

Petter

Petter is right.

In case you are still wondering what kind of string manipulation is needed,
the StartsWith() method in the String class is useful. However, if you
have two namespace strings ns1 and ns2,

ns1.StartsWith( ns2 )

will NOT always tell you whether ns1 is nested in ns2. For example, when
ns1 is "Foo.Bar" and ns2 is "Foo.B", the above expression returns true
while ns1 is not really nested in ns2.

Given that namespaces are period-separated, the following trick will solve
the problem:

(ns1 + ".").StartsWith( ns2 + ".")

HTH,

- Zhanyong Wan

Visual Studio and .NET Setup

This posting is provided "AS IS" with no warranties, and confers no rights.
Use of included samples (if any) is subject to the terms specified at
http://www.microsoft.com/info/cpyright.htm
 
Zhanyong Wan said:
Given that namespaces are period-separated, the following trick will solve
the problem:

(ns1 + ".").StartsWith( ns2 + ".")

Actually,

ns1.StartsWith(ns2 + ".")

should be sufficient to test for a nested namespace ;-)

Jens.
 
Back
Top