Using Generic Classes as Type Parameters

  • Thread starter Thread starter Levi
  • Start date Start date
L

Levi

class A<Ta>
{
public A() { }
}

class B<TA, Ta>
where TA : A<Ta>
{
public B() { }
}

class Program
{
static void Main(string[] args)
{
B<A<int>, int> var = new B<A<int>, int>();

//how I'd like to do it
//B<A<int> > = new B<A<int> >();
}
}

Is there some combination of syntax that'll let me declare a variable
of type B as I'd like to do it? It's a bit clunky having to say that I
want int twice.
 
Levi,

No, there is not a way to do it. You will have to declare it like that
on the type level every time. Type parameters on the method level can be
implied, but at the type level (except when indicating the type in static
methods), they can not be.

Hope this helps.
 
Levi,

One other thing, you can always declare a type alias with the using
statement, and then use that. At the top of your file, you can do:

using MyGenericB = B<A<int>, int>;

Then, in your code, you can do:

MyGenericB var = new MyGenericB();

And it will compile fine.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Back
Top