This is a mirror of official site: http://jasper-net.blogspot.com/

C# 2.0 Aliases

| Sunday, March 6, 2011
Introduction

Undeniably, the discussion on aliases cannot be tackled without a quick history on their scope of use. Of course, to attack this subject, a brief lecture on namespaces is necessary so here it goes. C# namespaces allow you to create a system to organize your code in a hierarchical manner. An example of this is given below:

namespace Apresss
{
    namespace Data
    {
        public class DataManager
        {
        
        }
    }
    
    namespace IO
    {
        public class BluetoothReader
        {
        
        }
    }
}

The items within can either be accessed via the fully qualified type name, as illustrated in the example below:

Apress.Data.DataManager dman = new Apress.Data.DataManager();

Or, by explicitly scoping to items of that namespace with the using declaration. An example of this is given below:

using Apress.IO;
class Program
{
    static void Main(string[] args)
    {
        Apress.Data.DataManager dman = new Apress.Data.DataManager();
        BluetoothReader btooth = new BluetoothReader();
    }

}

The only purpose of the using command in this context is to save you typing and make your code simpler. It does not, for example, cause any other code or libraries to be added to your project. Besides providing us with the ability to permit types in a given namespace without qualification, the using keyword can also provide us the ability to create aliases for a namespace. An example of this is provided below:

using aio = Apress.IO;

and the ability to provide aliases for types as in the example below:

using Apress.IO;
using aio = System.Console;
class Program
{
    static void Main(string[] args)
    {
        aio.WriteLine("Aliased Type."); 
    }

}

In the above example, the type System.Console has been given a new name aio. The code inside the program�s Main method can now access members of Console through this alias.

The most common use of aliases is in situations where name collisions occur between two libraries, or when a small number of types from a much larger namespace are being used. Examine the sample listed below:

namespace Apress
{
    namespace Data
    {
        public class DataManager
        {
        
        }
    
        public class BluetoothReader
        {
        
        }
    }
    
    namespace IO
    {
        public class BluetoothReader
        {
        
        }
    }
}

Read more: Codeproject

Posted via email from Jasper-net

0 comments: