Dlongnecker
Dlongnecker

Reputation: 3047

Weird C# namespace issue

I've got a project with several namespaces and many classes contained within one of them ->

Some.Namepsace. (namespace)
               ExistingClass (class)
               ExistingClass2 (class)
               Constants (class)
                        .Enum (enum)

Within this project I created a class, but with an incorrect namespace like so

namespace Some.Namespace.Some.Namespace
{
    public class NewClass {}
}

Now Some.Namespace.ExistingClass cannot resolve a reference to Some.Namespace.Constants.Enum - it appears to be looking for Some.Namespace.Some.Namespace.Constants.Enum.

Any idea why? NewClass does not reference anything, and is not referenced by anything so I don't see how it's namespace could affect any other components. I fixed the namespace issue on NewClass, and that fixes it.

Upvotes: 1

Views: 1446

Answers (2)

Dlongnecker
Dlongnecker

Reputation: 3047

This must have something to do with the way C# in visual studio/csc attempts to resolve references. It would appear it goes something like this:

  • Look relative to the namespace of the calling object
  • If such a namespace is not found, attempt to look up the reference as if it's absolute

In my case, before I added Some.Namespace.Some.Namespace.NewClass, when VS tried to resolve the reference from Some.Namespace.ExistingClass to Some.Namespace.Constants.Enum, it first attempted a relative namespace lookup (starting from ExistingClasse's Some.Namespace), found no such namespace. It then attempted an absolute lookup and found it.

After I added Some.Namespace.Some.Namespace.NewClass, it found the namespace, noticed the object was not there, and decided to discontinue searching.

Upvotes: 0

Szymon Rozga
Szymon Rozga

Reputation: 18168

A class inside Some.Namespace.Some.Namespace will try to resolve Some.Namespace.Constants.Enum as: Some.Namespace.Some.Namespace.Constants.Enum, not Some.Namespace.Constants.Enum.

It would work if you tried to refer to the Enum as: global::Some.Namespace.Constants.Enum.

Upvotes: 6

Related Questions