Anyone who has already written one or the other program in Visual Studio with C# probably knows the following problem. Sometimes you use different libraries (Dlls) from different developers/vendors. Partly also libraries that fulfill similar purposes. This might go well, but it doesn’t have to.
Often you will get confronted with an error message like this: “‘XYZ’ is an ambiguous reference between ‘LibraryA.XYZ’ and ‘LibraryB.XYZ'”
What next? In the following I’ll explain how to solve this kind of error by taking the example of the AForge library. For instance we profess that we included the following using-directives into our program.
using System.Drawing; using AForge.Imaging;
So now, if we use the class “Image” in our program, we will see the following error message, which result from the fact that there are two “Image” classes referenced. One in the System.Drawing namespace as also one in the AForge.Drawing namespace. Visual Studio (and later on it’s compiler) doesn’t know which Image class to use.
One way to solve this would be to weigh which one of the both classes is used more frequently and then remove the using-directive for the namespace which contains the implementation which is used less frequently. But then you had to specify the full path everytime you want to use the class which isn’t referenced as using directive.
Image img = AForge.Imaging.Image.FromFile(imagePath);
However this is (depending on the number of calls of this class and the length and nesting of the namespaces) really awkward.
Much simpler and more elegant (atleast to my mind) is to make an alias for a namespace. Setting an alias can be done directly when setting up the using directive. On the basis of our example, we could rewrite the Aforge using directive as follows.
using System.Drawing; using AF = AForge.Imaging;
From now on we always can write a simple “AF.” instead of the much longer “AForge.Imaging.”. On the one hand this solves the problem of the ambiguous references and on the other hand it helps us to easily distinguish between the different references.
Image img = AF.Image.FromFile(imagePath);
This was easy, wasn’t it? Now let me know if you already used namespace aliases or if this topic was news to you?
0 Comments