Thursday, October 05, 2006

:: Operator

The namespace alias qualifier operator.

I ran across this operator for the first time the other day in a c# application (an XNA app, pretty cool stuff :) ). Anyhow, it looked like some c / objective c code at first to me. I'd never seen this used in c# before.

Basically here's what it does, with a not so elegant example:

(Here's a class that belongs to an ungodly deep namespace)

namespace some.really.big.nested.namespac {

public SomeClass {

public enum Number {

small,

medium,

large

}

}

}

(Here's a class that needs to use the above class, but this class also has a method with the same name as the above class name)

namespace smallNamespace {

class SomeOtherClass {

public void Number(int size) {

if((int)some.really.big.nested.namespace.Number.small == size)

// do something

}

}

}

Now that is pretty ugly stuff..

In a large project you may end up with a situation where a class name in one namespace is used in another namespace as a field, method etc. In which case you would have to use the fully qualified name to let the compiler know which 'thing' your talking about.

Now here is a better way to do this, it shrinks down your code, and is easy to understand:

namespace smallNamespace {

using bigNameSpace = some.really.big.nested.namespac;

class SomeOtherClass {

public void Number(int size) {

if((int)bigNameSpace::Number.small == size)

// do something

}

}

}

Create a namespace alias with the using statement.

the '::' is placed between the two identifiers, and invokes a different lookup for the item.

Another common use of this variable is for the global namespace

"global::Console.WriteLint("Hello World");"

No comments: