tags:

views:

149

answers:

5

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

+1  A: 

Yes. use the using directive.

EDIT: If you search with the term "c# alias", you will find an answer easily, as well.

shahkalpesh
This is correct. http://www.codeproject.com/KB/dotnet/Data_Type_Alias__Net.aspx shows an example.
awright18
+1  A: 

Yes, using can do that

using q = System.Int32;
Arve
+12  A: 

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 = ...
Dewfy
+1, Never considered using it this way
Nick Craver
+4  A: 

using XDoc = System.Xml.Linq.XDocument;

However, it only survives for the compilation of the one C# file. You cannot export this alias.

Frank Krueger
+7  A: 

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>;
Eric Lippert