Saturday, April 9, 2011

Using Types with same name and namespace from two different assemblies

Ocassionally, you may observe that one type is present in two different assemblies ( Say, MyClass is preseny in the assembes LibraryOne.dll and LibraryTwo.dll.). Using MyClass from both assemblies is not an issue as long as they belongs to two different name spaces i.e. if MyClass in LibraryOne.dll is in namespace LibraryOne.MyClass and MyClass in LibraryTwo.dll is in namespace LibraryTwo.MyClass, you can reference both assemblies together and use both classes in your project without any issues.

It becomes tricky (or may be ugly) when types from different assemblies share the same name and same namespaces. When you compile the application, your compiler gets confused and complains that type is found at two different places. Most of the tim,e this is not expected as it leads to a bad design. But sometimes you may find this situation unvoidable, for example, when you have to supoort backward compatibility in the application.
 Here are the steps to resolve the issue:
 1. Create Aliases for the assemblies:

  • Open the references node in the visual studio and select the referenced assembly (LibraryOne.dll)
  •  Right click and select properties
  • In Aliases field, set an approprita aliase for the aseebmly.
  • Similarly, set the alias for the second assembly

2. Use the Alias to specify the namepsace and type from a particular assembly:
  • Refer the assembly alias on top of the class file using extern 

This way your compiler would know that it has to refer the Type which is defined in the assemlbly having alias LibVersion1 (i.e. LibraryOne.dll)

No comments:

Post a Comment