Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# typedef generics

I am using a shorthand version for a class, which looks like this:

using NodeSteps = Tuple<Node, int>;

Node is a class defined by myself. This works fine usually, but the problem here is, is that Node is a generic requiring a struct.

My questions are as follows:

1. How are these typedefs called in C#. I know they are not exactly typedefs, but it was the most similar thing I could think of.

2. How can I make a generic version?

using NodeSteps<T> = Tuple<Node<T>, int>;

I noticed this is not the way to do it. I also would like to specify T is a struct.

like image 869
Aart Stuurman Avatar asked Nov 05 '13 13:11

Aart Stuurman


2 Answers

Use

class NodeSteps<T> : Tuple<Node<T>, int>
{
}

This is the closest equivalent to a typedef I know of. If there are any non-default constructors, you would need to declare them, though.

like image 62
PMF Avatar answered Nov 02 '22 23:11

PMF


  1. They are called aliases.

  2. No, this isn't possible. C# Language spec:

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

Therefore, using x<T> = List<T> or something similar isn't possible.

You may use a class (see the other answers(s)) instead.

like image 26
Matten Avatar answered Nov 03 '22 00:11

Matten