Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create an alias for a generic class in C#?

How can I do the following in C#? What is the right way to write the first line of this code snippet?

using KVP<K, V> = System.Collections.Generic.KeyValuePair<K, V>;  class C { KVP<int, string> x; } 
like image 589
Hosam Aly Avatar asked Jan 11 '09 20:01

Hosam Aly


People also ask

What is type aliasing?

Type aliases Type aliases provide alternative names for existing types. If the type name is too long you can introduce a different shorter name and use the new one instead. It's useful to shorten long generic types.

Can we create a generic method inside a non generic class?

Yes, you can define a generic method in a non-generic class in Java.


2 Answers

You can't, basically. You can only use fixed aliases, such as:

using Foo = System.Collections.Generic.KeyValuePair<int, string>;  class C { Foo x; } 
like image 173
Marc Gravell Avatar answered Oct 13 '22 02:10

Marc Gravell


In some cases you can go with inheritance:

public class MyList<T1, T2> : List<Tuple<IEnumerable<HashSet<T1>>, IComparable<T2>>> { }  public void Meth() {     var x = new MyList<int, bool>(); } 

Though not in your particular case, as KeyValuePair is sealed :-(

like image 42
Mike Tsayper Avatar answered Oct 13 '22 04:10

Mike Tsayper