Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to declare an alias with .net type?

Tags:

c#

alias

Is it possible to declare an alias with .net type ? in c# and if so how ?

like image 717
TonyP Avatar asked Feb 20 '10 15:02

TonyP


People also ask

What is an alias in C#?

Introduction. Namespaces in C# serve two main purposes: to organize classes and functionality and to control the scope of classes and methods. 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.

Where and how alias is used in C#?

By using an external assembly alias, the namespaces from each assembly can be wrapped inside root-level namespaces named by the alias, which enables them to be used in the same file. The extern keyword is also used as a method modifier, declaring a method written in unmanaged code.

Is C++ is an alias of C#?

C++ is not the alias of C# programming language.

Which of the following represents the correct usage of alias for classes?

Namespace Alias Qualifier(::) makes the use of alias name in place of longer namespace and it provides a way to avoid ambiguous definitions of the classes. It is always positioned between two identifiers. The qualifier looks like two colons(::) with an alias name and the class name. It can be global.


2 Answers

As others have said, use the "using alias=type;" form of the using directive. Couple things about that:

1) It's got to be the first thing in the file or the namespace. (Unless you have extern alias directives of course; they go before the using directives.)

2) The alias is not a true type. A lot of people would like to see:

using PopsicleCount=System.Int32;
using GiraffeCount=System.Int32;
...
PopsicleCount p = 123;
GiraffeCount g = p; // ERROR, can't convert a count of giraffes into a count of popsicles

But we don't support that feature. It's a true alias; we just substitute the alising type in for the aliased identifier when we see it; p and g are both of type int.

3) The alias only applies in the file or namespace declaration it appears in. If you want to use an alias in every file in your program, you'll have to write it in every file in your program.

4) Aliases cannot be parameterized on the alias name side, though they can be closed generic types on the type side. That is, this is legal:

using GiraffeList = System.Collections.Generic.List<Giraffe>;

but this is not:

using Frobtionary<T> = System.Collections.Generic.Dictionary<Frob, T>;
like image 173
Eric Lippert Avatar answered Oct 08 '22 08:10

Eric Lippert


For example:

using MatchBuilderFactoryFunc = System.Func<
    IndexerBase.RequestMatching.RequestFreeTextAnalyzeParameter,
    System.Collections.Generic.IEnumerable<
        IndexerBase.RequestMatching.IMatchBuilder>>;

And after all use it as simple type:

MatchBuilderFactoryFunc f = ...
like image 31
Dewfy Avatar answered Oct 08 '22 07:10

Dewfy