Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Both a generic constraint and inheritance

I have this scenario:

class A<T> 

I want a constrain of type Person like

class A<T> where T: Person

and I want A to inherit from B too.

example:

class A<T> : B : where T: Person

or

class A<T> where T: Person,  B

how can I do it?

like image 795
Zinov Avatar asked Apr 08 '14 14:04

Zinov


People also ask

Can generic class be inherited?

You cannot inherit a generic type. // class Derived20 : T {}// NO!

Can a generic class have multiple constraints?

Multiple interface constraints can be specified. The constraining interface can also be generic.

What is a generic constraint?

4/7 Generics Constraints. Previous: Next: Generics Interfaces. Constraints are like rules or instructions to define how to interact with a generic class or method. They can restrict the parameter that will be replaced with T to some certain type or class or have some properties, like to be new instance of class.


2 Answers

class A<T> : B where T : Person
like image 50
Radu Pascal Avatar answered Oct 13 '22 13:10

Radu Pascal


You can't inherit from more than one class in C#. So you can have

A<T> inherites from B and T is Person (Person is either class or interface):

class A<T>: B where T: Person {
  ...
}

A<T> doesn't necessary inherites from B; but T inherites from B and implements Person (Person can be interface only):

class A<T> where T: Person, B {
  ...
}

It seems that you want case 1:

// A<T> inherites from B; 
// T is restricted as being Person (Person is a class or interface)
class A<T>: B where T: Person {
  ...
}
like image 44
Dmitry Bychenko Avatar answered Oct 13 '22 13:10

Dmitry Bychenko