Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scope-resolution operator :: versus member-access operator . in C#

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?

like image 697
user541686 Avatar asked Jan 19 '11 03:01

user541686


People also ask

What is a scope resolution operator :: used for?

The scope resolution operator :: is used to identify and disambiguate identifiers used in different scopes. For more information about scope, see Scope.

What is the difference between scope resolution operator and dot operator in C++?

The former (dot, . ) is used to access members of an object, the latter (double colon, :: ) is used to access members of a namespace or a class.

What is the purpose of the :: operator in C++?

The scope resolution operator is used to reference the global variable or member function that is out of scope. Therefore, we use the scope resolution operator to access the hidden variable or function of a program. The operator is represented as the double colon (::) symbol.

What is :: called in CPP?

In C++ the :: is called the Scope Resolution Operator. It makes it clear to which namespace or class a symbol belongs.


2 Answers

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.

MSDN info here

like image 146
Neil Avatar answered Nov 11 '22 06:11

Neil


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
   }
}

http://download.microsoft.com/download/0/B/D/0BDA894F-2CCD-4C2C-B5A7-4EB1171962E5/CSharp%20Language%20Specification.htm

like image 41
Robert Levy Avatar answered Nov 11 '22 06:11

Robert Levy