In C#, what's the difference between A::B
and A.B
? The only difference I've noticed is that only ::
can be used with global
, but other than that, what's the difference? Why do they both exist?
Asked
Active
Viewed 3,383 times
7

user541686
- 205,094
- 128
- 528
- 886
2 Answers
6
the :: operator only works with aliases global is a special system provided alias.
so ... this works:
using Foo = System.ComponentModel;
public MyClass {
private Foo::SomeClassFromSystemComponentModel X;
}
but not this:
public MyClass {
private System.ComponentModel::SomeClassFromSystemComponentModel X;
}
This lets you escape from the hell of sub namespaces that can come about when you are integrating with a library where they have:
namespace MyAwesomeProduct.System
{
}
And you in you code have
using MyAwesomeProduct;
global:: lets you find the real System.

Neil
- 1,605
- 10
- 15
-
Hm... you're explaining why `global::` is useful, but not exactly the difference between `::` and `.`... – user541686 Jan 19 '11 at 04:21
-
2:: *only* works with alases - that way if someone declares a name space or a sub name space later that has the same namespace as you alias your code will be fine. It is the get out of jail operator for sub namespace resolution if you will. You have control of alaises in your file - but other people control the namespaces of the libs you use. :: gives you control when other namespaces contrive to change the meaning of your code. – Neil Jan 19 '11 at 04:29
5
with :: you can do things like...
extern alias X;
extern alias Y;
class Test
{
X::N.A a;
X::N.B b1;
Y::N.B b2;
Y::N.C c;
}
and there are times when . is ambiguous so :: is needed. here's the example from the C# language spec
namespace N
{
public class A {}
public class B {}
}
namespace N
{
using A = System.IO;
class X
{
A.Stream s1; // Error, A is ambiguous
A::Stream s2; // Ok
}
}

Robert Levy
- 28,747
- 6
- 62
- 94
-
So you're saying that `::` only works with namespaces, whereas `.` works with everything except `global`? – user541686 Jan 19 '11 at 04:22
-
yes, the fact that :: is only for namespaces means you can use it to resolve ambiguity which can't be resolved by . – Robert Levy Jan 19 '11 at 04:25