Zinov
Zinov

Reputation: 4119

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?

Upvotes: 14

Views: 6929

Answers (5)

Fruchtzwerg
Fruchtzwerg

Reputation: 11389

In case an interface shall be applied as well:

public class ChildClass<T> : BaseClass where T : class, IInterface

Upvotes: 0

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

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 {
  ...
}

Upvotes: 4

Michal Ciechan
Michal Ciechan

Reputation: 13888

There is no multiple inheritance in C#, therefore you cannot enforce that a type inherits from multiple classes.

Sounds like your structure is incorrect.

To ensure both are implement, either one of them has to be an interface, or one of them has to implement the other.

If you mean T can implement B or Person then, then there should be some abstract base class/interface that B and Person share which you restrict to that

Upvotes: -1

PiotrWolkowski
PiotrWolkowski

Reputation: 8782

Are you asking how to express this structure in C#? If so below one example:

class Program
{
    static void Main(string[] args)
    {
        B a1 = new A<Person>();
        B a2 = new A<ChildPerson>();
    }
}
class Person
{
}

class ChildPerson : Person
{
}

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

class B
{
}

Upvotes: 2

Radu Pascal
Radu Pascal

Reputation: 1337

class A<T> : B where T : Person

Upvotes: 30

Related Questions