megaman
megaman

Reputation: 1101

Namespace and class have the same name

I have inherited a large c# project. One of the classes has a namespace and class which share the same name. As a result when making an instance of the class i have to do this:

using xxx.existingName
IinterfaceName dog = new existingName.existingName();

Since the existing class has an interface i am able to avoid having existingName.existingName on the left of the =. Using var dog would also do this. However i also want to avoid existingName.existingName being used on the right hand side because it is less readable.

Is there any way to do this without renaming the existing code?

Upvotes: 0

Views: 3909

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460268

You could use an alias to make this more readable(well, not with these names):

using AliasForName = existingName;

...

IinterfaceName dog = new AliasForName.existingName();

If the original author would have looked at this MSDN article, he would have used a different name in the first place:

X DO NOT use the same name for a namespace and a type in that namespace . For example, do not use Debug as a namespace name and then also provide a class named Debug in the same namespace. Several compilers require such types to be fully qualified.

By the way, you should really apply capitaliation conventions.

Upvotes: 1

adjan
adjan

Reputation: 13684

You could rename the class or the namespace via the using directive:

using ClassAlias = Test.Test;
using NamespaceAlias = Test;

public class Program
{
    public static void Main()
    {
        ClassAlias a = new ClassAlias();
        NamespaceAlias.Test t = new NamespaceAlias.Test();
    }
}

namespace Test{
    public class Test{}
}

Upvotes: 3

Related Questions