views:

55

answers:

3

I saw the following namespace implementation in an article and i really can't get the point why they did so?

using sysConfig =System.Configuration ;

string connectionString = sysConfig.ConfigurationManager.
                         ConnectionStrings["connectionString"].ConnectionString;

I know It can be easily implemented like this,

string connectionString = System.Configuration.ConfigurationManager.
                         ConnectionStrings["connectionString"].ConnectionString;

Any suggestion when to use the first type...

+5  A: 

Two reasons for using namespace aliases:

  1. To resolve conflicts between namespaces
  2. To make code more readable (shorter namespace names)

In the example you provided, I don't see the benefit though. It just confuses the person reading the code.

Philippe Leybaert
+1  A: 

Namespace aliases are good when you want the namespace references to have a defined scope, contrary to the global scope when you put put your using references on top of the class file.

For example, if you have a function that uses multiple classes from System.IO and you don't want the other parts of the class to reference the namespace, you just apply it inside the function as a namespace alias.

One important affected behavior in Visual Studio is Intellisense.

SiN
+4  A: 

Let's say you want to use a library that contains a class called "Lib.IO.File". But you also want to use System.IO.File. This would cause a problem:

using System.IO;
using Lib.IO;
class Program
{
    static void Main(string[] args)
    {
        File f; // ambiguous type! which File class do you mean?
    }
}

In such case, you can do:

using Sys = System.IO;
using Lib = Lib.IO;
class Program
{
    static void Main(string[] args)
    {
        Sys.File f1;
        Lib.File f2;
    }
}

Though in your example, the purpose is obviously typing less namespaces.

Gorkem Pacaci