Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is possible T<T>

Tags:

c#

I have some class, for example A, and others who extended A (A1,A2). The A is a container - it has only fields, any methods and properties.

Another class is B<T> where T : A, and extends of B (B1, B2)

Is it possible do that in c#?

public List<T<T1>> DoSomething(object parameter) 
                                      where T : B<T1>, new() where T1 : A, new()

In that method i must dynamic create T (B1 or B2 or B3) object and fill that generic object dynamic created T1 objects (A1, A2, A3). Yup i probably can use Activator, but use new T() will be better and use less casts

like image 556
user1091406 Avatar asked Jun 04 '26 19:06

user1091406


2 Answers

You don't need T<T1>

To clean it up a little:

public List<T> DoSomething<T, T1>(object parameter) 
      where T : B<T1>, new()   // this specifies T<T1> already
      where T1 : A, new()
{
}

And assuming A and B have default constructors, you don't need the new() constraints.

like image 70
Henk Holterman Avatar answered Jun 07 '26 08:06

Henk Holterman


You could do it, but it would be annoying to use:

public List<TB> DoSomething<TA, TB>(object parameter)
    where TA : A, new()
    where TB : B<TA>, new()
{ }

var list = DoSomething<A1, B1<A1>>(3);

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!