How to use an alias type as a generic type parameter in C# [duplicate]
Asked Answered
E

2

0

How do you pass an alias type defined by using to the generic class?

I tried the following code:

using ID = Int32; // it might be replaced with `String`.
using CC = C<ID>;

public class C<T> {
    T id;
}

and there will be an error:

Error CS0246 The type or namespace name 'ID' could not be found (are you missing a using directive or an assembly reference?)

But the using directive is right above the line where the error occurs. Did I miss something?

Enter answered 28/7, 2017 at 6:26 Comment(3)
What are you trying to achieve?Catamnesis
This does not seem to be possible at the moment, plase see the first comment hereDespiteful
While the linked duplicate cites the specification, there is a way around it, declare ID in the outer namespace and CC in an inner namespace. The fact that they're in the same namespace is the problem here.Purse
D
0

I do not really know what you are trying to achieve with this, but you can, however, do something similar with inheritance

public class CC : C<ID>
{
}

The class CC will derive from C<T> with a concrete type. Hence CC.T will be of type Int32 (or whatever).

Despiteful answered 28/7, 2017 at 6:30 Comment(0)
C
-1

Don't use an alias.

public class C<T> {
   T id;
}

...

void Foo() {
  var x = new C<Int32>();

  var y = new C<string>();
}
Catamnesis answered 28/7, 2017 at 6:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.