In his project there were more than 4 class library projects used within his application. But by mistake he had created the same namespace with same class name within the two class library project. After adding the references of that class library in his main project, when he tried to create an instance of that class, he got the following error.
Error 1
The type ‘Lib1.PatientDataContext’ exists in both ‘d:\TFS\Lib1\bin\Debug\Lib1.dll’ and ‘d:\TFS\Lib2\bin\Debug\Lib2.dll’
It means the C# compiler gets confused that which assembly it has to use for creating an instance of the class. That’s why it throws an above error.
So he asked me to resolve his issue. well, i have never faced this type of error before. So i did some googling and came to the solution that by using extern alias provided in C#, above issue can be resolve. How ? Let’s see this practically by creating that scenario.
In Visual studio, let’s create one console application and named it as – NameSpaceCollisionApp. Now within the same solution of the application add the two new class library project. In each class library assembly add one new class named – PatientDataContext.cs. But keep in mind that both of these class are within same namespace. The code of both the class looks like this –
ClassLibrary1 / PatientDataContext.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | namespace DataServiceFactory.DataContext
{
public class PatientDataContext
{
public PatientDataContext()
{
}
public override string ToString()
{
return "From Class Library 1" ;
}
}
}
|
ClassLibrary2 / PatientDataContext.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | namespace DataServiceFactory.DataContext
{
public class PatientDataContext
{
public PatientDataContext()
{
}
public override string ToString()
{
return "From Class Library 2" ;
}
}
}
|
REPORT THIS AD
When you build the application, you’ll get the error highlighted above. So let’s resolve it by following the below steps.
Step-1: In the solution explorer, expand the “References” folder and select the required assembly name then right click on it and open its property window.
Step-2: In the property window, change the aliases name from “global” to “Service1 (Whatever you want)”.
Step-3: Same way follow the Step-2 for ClassLibrary2 reference also.
Step-4: Now to use it in your main application, you need to add – extern alias “alias name”; line of code to the top of your source file, something like this –
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | extern alias Service1;
extern alias Service2;
using System;
namespace NameSpaceCollision
{
class Program
{
static void Main( string [] args)
{
var object1 = new Service1.DataServiceFactory.DataContext.PatientDataContext();
var object2 = new Service2.DataServiceFactory.DataContext.PatientDataContext();
Console.WriteLine(object1);
Console.WriteLine(object2);
Console.ReadLine();
}
}
}
|
And we are done. Hope you like this post and hope it may help to my future readers.