Explain the advantages and limitations of using Aliases in C#?

Questions by sophiya_261978

Showing Answers 1 - 9 of 9 Answers

Aliases can be useful in the case if you are using a lenthy namespace.You can create an aliase for namespace and can acess its classes via alias.

On the negative side it can cause some conflicts if you declare any class with same name in that scope.But finally it can be resolved through scope resolution operator.

  Was this answer useful?  Yes

PeterVH

  • Aug 19th, 2011
 

Well, it is needed if for some reason you have conflicting names. Silly example, but suppose you declare a variable with the name DateTime, and to be very funny (sarcasm) you also define a variable named System.

When you later on want the normal DateTime.Now you are in trouble. First off, DateTime will be your local variable. Okay, you can try System.DateTime but that won't work because you also have a variable named System.

So what to do? Here comes the alias to save the day (cfr example)

Code
  1. using DateTimeAlias = System.DateTime;

  2.  

  3. namespace WindowsFormsApplication4

  4. {

  5.     public partial class Form4 : Form

  6.     {

  7.         public Form4() { InitializeComponent(); }

  8.  

  9.         private void button1_Click(object sender, EventArgs e)

  10.         {

  11.             // April fools? It is an example okay, not very likely to happen in real life..

  12.             const int System = 5;

  13.             const int DateTime = 5;

  14.  

  15.             Debug.WriteLine("But I can still get the Now value by using my alias! " + DateTimeAlias.Now);

  16.         }

  17.     }

  18. }

  Was this answer useful?  Yes

LordAlex

  • Nov 3rd, 2011
 

C# provides a set of predefined struct types called the simple types. The simple types are identified through reserved words, but these reserved words are simply aliases for predefined struct types in the System namespace.
{sbyte, byte, short, ushort, int, uint, long, ulong, and char}

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions