Question

I just found the following code and don't know why it is done this way. Risk for conflict?

using DiffTreeNode = EPiServer.Enterprise.Diff.TreeNode;

And then in the class it is used as usual.

Why would you do something like this?

Was it helpful?

Solution

That's a using directive (see here) rather than a using statement and very similar to something like using System.Text;.


A using statement allows you to automatically clean up stuff without mucking about with try/catch/finally blocks:

using (Sometype xyzzy = new SomeType()) {
    // Do whatever with xyzzy
}
// xyzzy is gone, pining for the fjords.

The using directive imports a namespace so that you don't have to explicitly use the namespace to prefix all the types within it. Your particular variant basically creates an alias for the EPiServer.Enterprise.Diff.TreeNode namespace so you can simply refer to it as DiffTreeNode beyond that point. In other words, after the directive:

using DiffTreeNode = EPiServer.Enterprise.Diff.TreeNode;

the following two statements are equivalent:

EPiServer.Enterprise.Diff.TreeNode.SomeType xyzzy =
    new EPiServer.Enterprise.Diff.TreeNode.SomeType();
DiffTreeNode.SomeType xyzzy = new DiffTreeNode.SomeType();

and I know which I'd prefer to type in.


Now you may be asking why, if the directive can let you use the types within a namespace on their own, why do we not just do:

using EPiServer.Enterprise.Diff.TreeNode;
SomeType xyzzy = new SomeType();

My bet would be, though I'll wait for the likes of Jon Skeet to confirm or deny this :-), that it's to cover the case where you have two or more namespaces with identically named types. That would allow:

using Bt = Trees.BinaryTree;       // Has Tree type.
using Rbt = Trees.RedBlackTree;    // Annoyingly, also has Tree type.
Tree t = new Tree();               // Is this binary or redbalck?
Bt.Tree t1 = new Bt.Tree();        // Definite type.
Rbt.Tree t2 = new Rbt.Tree();      // Ditto.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top