Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When would I use an alias on a using Directive?

Tags:

c#

So I was reading over the MSDN docs and came across:

http://msdn.microsoft.com/en-us/library/sf0df423.aspx

What is a practical use of using an alias for using directives?

I get what is does, I just dont get WHY I could want to use it.

like image 261
RJP Avatar asked Apr 13 '12 20:04

RJP


People also ask

What is the purpose of the using directive?

The using directive allows you to abbreviate a type name by omitting the namespace portion of the name—such that just the type name can be specified for any type within the stated namespace.

What is an alias in C#?

Type aliasing is a little known feature for C# and it comes in handy when you would like to alias a specific method or class from a namespace for the sake of clarity. At the heart of these features is the using keyword.

How to use alias in using c#?

using System; // Using alias directive for a class. using AliasToMyClass = NameSpace1. MyClass; // Using alias directive for a generic class.

Should using directives be inside or outside the namespace?

As a rule, external using directives (System and Microsoft namespaces for example) should be placed outside the namespace directive. They are defaults that should be applied in all cases unless otherwise specified.


1 Answers

It's useful if you have a class of the same name in two different namespaces. When that happens you have two choices. using one namespace and not another (meaning use the fully qualified name for the other one), or using one namespace normally and using another with an alias. Since the alias is shorter than the fully qualified name it's still easier and more convenient.

Obviously the best option is to just not have public classes of the same name in different namespaces, especially if there's any chance someone would want to use both in the same class.

like image 86
Servy Avatar answered Oct 13 '22 05:10

Servy