22

Here's the problem, you include multiple assemblies and add 'using namespaceX' at the top of your code file.
Now you want to create a class or use a symbol which is defined in multiple namespaces, e.g. System.Windows.Controls.Image & System.Drawing.Image

Now unless you use the fully qualified name, there will be a crib/build error due to ambiguity inspite of the right 'using' declarations at the top. What is the way out here?

(Another knowledge base post.. I found the answer after about 10 minutes of searching because I didn't know the right keyword to search for)

Gishu
  • 134,492
  • 47
  • 225
  • 308
  • As the accepted answer stated, use alias but try to be consisted across the entire code base (just one alias for one namespace / class and they should be easy to distinguish). – kokos Sep 14 '08 at 13:48

2 Answers2

34

Use alias

using System.Windows.Controls;
using Drawing = System.Drawing;

...

Image img = ... //System.Windows.Controls.Image
Drawing.Image img2 = ... //System.Drawing.Image

C# using directive

Wipqozn
  • 1,282
  • 2
  • 17
  • 30
aku
  • 122,288
  • 32
  • 173
  • 203
  • Deleting my answer to reduce clutter. 'Namespace Alias Qualifier' - now that name is something I would have never have figured out to use as a search keyword. :) – Gishu Sep 14 '08 at 11:04
  • Yep, it's a very good example of Single Responsibility Principle violation. But it's too fun to show it to you colleagues and hearing "Wow!, FTW?!" – aku Sep 14 '08 at 11:10
  • The name for the `using = ...` construct is _using alias directive_, and it is documented [here](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-directive) (the link in the answer is now dead). _Namespace alias qualifier [operator]_ is the name of the `::` operator that separates a namespace alias from the type name: `Drawing::Image`; while `Drawing.Image`, as shown in the answer, works too, it can be ambiguous - see the [docs](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/namespace-alias-qualifier). – mklement0 Oct 19 '20 at 18:05
6

This page has a very good writeup on namespaces and the using-statement:

http://www.blackwasp.co.uk/Namespaces.aspx

You want to read the part about "Creating Aliases" that will allow you to make an alias for one or both of the name spaces and reference them with that like this:

using ControlImage = System.Windows.Controls.Image;
using System.Drawing.Image;

ControlImage.Image myImage = new ControlImage.Image();
myImage.Width = 200;
Espo
  • 41,399
  • 21
  • 132
  • 159