sookie
sookie

Reputation: 2517

Identical class names across different namespaces - how to access class via immediate parent namespace?

Imagine I have the following namespace structure:

- components
--- x
----- [MyComponent]
----- [YourComponent]
--- y
----- [MyComponent]
----- [YourComponent]

MyComponent and YourComponent are classes within the x and y namespaces.

My understanding was that I would be able to access the desired class by using components; and accessing them via x.MyComponent and y.MyComponent. This however doesn't seem to be the case, and I have to use the longer namespace name: components.x.MyComponent.

Is there a solution that would allow me to use the next immediate namespace in the hierarchy (e.g. x or y) to distinguish between the classes, rather than a 'full' or 'longer' namespace name (e.g. component.x and components.y)?

PS: I'm aware of the issues around class name sharing

Edit: Apologies, I'd like to know if there's a solution that doesn't require using aliases (if possible) unless it provides a workaround that allows me to specify x.MyComponent

Upvotes: 2

Views: 340

Answers (3)

Fabjan
Fabjan

Reputation: 13676

You have a few options here. You could:

A) Use an alias for the class:

using MyXComponent = components.x.MyComponent;
...
new MyXComponent();

B) Add using for one of these namespaces which contains the class (without alias):

using components.x;
...
new MyComponent(); // will create an x.MyComponent

C) Combine both approaches:

using x = components.x;  
using y = components.y;  
...
new x.MyComponent();
new y.MyComponent();

P.S.

The compiler needs to know which of the two classes you're looking for and if it finds two classes with the same name in namespaces included in using directives it throws a compile time error "xx is an ambiguous reference between this and that". Using of aliases allows us to help compiler to distinguish between the two.

Upvotes: 1

Prasad Telkikar
Prasad Telkikar

Reputation: 16049

We can use namespace aliasing to avoid long namespaces.

for example

using compX = components.x;
using compY = components.y;

Now we can distinguish same class present in different namespaces with the help of namespace aliasing

Like

  compX.MyComponent  //This will refer to MyComponent class from x namespcae

For more details: SO-Thread

Upvotes: 1

TheGeneral
TheGeneral

Reputation: 81493

I personally don't have classes with the same names, however you can use alias directives C# 6

// Using alias directive for a classes
using MyComponentX = components.x.MyComponent;
using MyComponentY = components.y.MyComponent;

Usage

MyComponentX instance1 = new MyComponentX();

Or if they are similar enough for the same name, Maybe generics?

Additional reading

using Directive (C# Reference)

Upvotes: 1

Related Questions