sporty_1993
sporty_1993

Reputation: 123

Resolving the Conflict of definitions in same namespaces

I have 2 same named classes defined in 2 different namespaces and I want to include both the namespaces as using statement in my c# file, Like below:

using A.B;
using C.B;

Lets say both A.B and C.B has definition for class foo and one of them is to be used based on a check like below:

if(check)
{
   // Use A.B ones class foo
}
else
{
   // Use C.B ones class foo
}

What is the best way to do this?

P.S. I can't change the name of the classes.

Upvotes: 0

Views: 327

Answers (3)

Md Tayeb Himel
Md Tayeb Himel

Reputation: 336

Suppose, you have a class Foo in NameSpaceA

namespace NameSpaceA
{
    class Foo
    {
        public string Sample { get; set; }
    }
}

and you have also class Foo in NameSpaceB

namespace NameSpaceA
{
    class Foo
    {
        public string Sample { get; set; }
    }
}

Now you can use this class in main method like this

using AFoo = NameSpaceA.Foo;
using BFoo = NameSpaceB.Foo;
if(check)
{
   AFoo afo = new AFoo();
}
else
{
   BFoo bFoo = new BFoo();
}

It is called aliasing Aliasing

You can also use this way. It is called fully qualified name link

if(check)
{
   NameSpaceA.Foo afo = new NameSpaceA.Foo();
}
else
{
   NameSpaceB.Foo bFoo = new NameSpaceB.Foo();
}

If this helps you please select this as a correct answer. It will help the community.

Upvotes: 0

Guru Stron
Guru Stron

Reputation: 141690

There is option to create alias for a namespace or a type. This is called a using alias directive:

using ABFoo = A.B.Foo;
using CBFoo = C.B.Foo;

if (check)
{
    ABFoo foo = new ABFoo(); // Use A.B ones class foo
}
else
{
    CBFoo foo = new CBFoo(); // Use C.B ones class foo
}

or use fully qualified class name:

if (check)
{
    A.B.Foo foo = new A.B.Foo(); // Use A.B ones class foo
}
else
{
    C.B.Foo foo = new C.B.Foo(); // Use C.B ones class foo
}

Upvotes: 4

Pavel Anikhouski
Pavel Anikhouski

Reputation: 23228

You can use fully qualified class name with namespace

if (check)
{
    var foo = new A.B.Foo();
}
else
{
    var foo = new C.B.Foo();
}

Upvotes: 2

Related Questions