Home > database >  Referencing type in different namespace with same prefix generates CS0234 error
Referencing type in different namespace with same prefix generates CS0234 error

Time:07-19

I'm confused why the following C# code won't compile, and instead generates the following:

error CS0234: The type or namespace name 'Module' does not exist in the namespace 'SomeName.Module.SomeName' (are you missing an assembly reference?)

using System;

namespace SomeName.Module.AnotherName
{
    public struct SomeStruct
    {
    }
}

namespace SomeName.Module.SomeName
{
    public class SomeClass
    {
        struct SomeNestedType
        {
            void SomeMethod(in SomeName.Module.AnotherName.SomeStruct someStruct) 
            { 
            }
        }
    }
}

I'm not aware of any namespace rules that would prevent it from finding the fully-qualified SomeName.Module.AnotherName.SomeStruct type.

CodePudding user response:

The problem is that SomeName is being resolved as the final part of the namespace SomeName.Module.SomeName, and Module is being resolved relative to that.

If you absolutely can't change your namespaces, you can use the global namespace alias to disambiguate:

void SomeMethod(in global::SomeName.Module.AnotherName.SomeStruct someStruct)

However, it would be better to just use different names. For example, if you have namespaces of SomeName1.Module.AnotherName and SomeName1.Module.SomeName2 you don't get this problem - and the code will be easier for humans to read as well as the compiler. (Obviously it wouldn't actually be that name, but I can only hope that you're not really using SomeName in the first place. Pick good but different names for the two parts of the namespace.)

  •  Tags:  
  • c#
  • Related