Using a 'using alias = class' with generic types?

C#.NetGenericsAlias

C# Problem Overview


So sometimes I want to include only one class from a namespace rather than a whole namespace, like the example here I create a alias to that class with the using statement:

using System;
using System.Text;
using Array = System.Collections.ArrayList;

I often do this with generics so that I don't have to repeat the arguments:

using LookupDictionary = System.Collections.Generic.Dictionary<string, int>;

Now I want to accomplish the same with a generic type, while preserving it as a generic type:

using List<T> = System.Collections.Generic.List<T>;

But that doesn't compile, so is there any way to achieve creating this alias while leaving the type as generic?

C# Solutions


Solution 1 - C#

No there is not. A type alias in C# must be a closed (aka fully resolved) type so open generics are not supported

This is covered in section 9.4.1 of the C# Language spec.

> Using aliases can name a closed constructed type, but cannot name an unbound generic type declaration without supplying type arguments.

namespace N2
{
	using W = N1.A;      	// Error, cannot name unbound generic type
	using X = N1.A.B;	    // Error, cannot name unbound generic type
	using Y = N1.A<int>;	// Ok, can name closed constructed type
	using Z<T> = N1.A<T>;	// Error, using alias cannot have type parameters
}

Solution 2 - C#

as shown at http://msdn.microsoft.com/en-us/library/sf0df423.aspx and http://msdn.microsoft.com/en-us/library/c3ay4x3d%28VS.80%29.aspx, you can do

using gen = System.Collections.Generic;
using GenList = System.Collections.Generic.List<int>;

and then use

gen::List<int> x = new gen::List<int>;

or

GenList x = new GenList();

however you have to replicate those using definitions at every file where you use them, so if you make some changes to them in the future and forget to update at every file, things will break badly.

I hope C# in the future Will treat aliases like the do with extension methods and let you define many of them in a file that you use elsewhere, then maintain them at one place and hide the internal unnecessary type mapping details from the type consumers.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questioncsharptest.netView Question on Stackoverflow
Solution 1 - C#JaredParView Answer on Stackoverflow
Solution 2 - C#George BirbilisView Answer on Stackoverflow