Both a generic constraint and inheritance
Asked Answered
Y

5

14

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?

Yearning answered 8/4, 2014 at 14:33 Comment(1)
I hope my edits were correct, but your original title makes me wonder. It doesn't seem like you want 'or', but that you want both the inheritance and the constraint.Maribeth
A
30
class A<T> : B where T : Person
Armadillo answered 8/4, 2014 at 14:36 Comment(0)
H
4

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 {
  ...
}
Hardunn answered 8/4, 2014 at 14:46 Comment(1)
I am not referring to multiple inherit is just a constrain over the generic type, and.... inherit from other classYearning
I
2

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
{
}
Interlay answered 8/4, 2014 at 14:41 Comment(1)
Good example, including the ChildPerson class for illustration. Maybe just for clarity add a note that you only added that class for illustration; it's not required for the requested functionality?Maribeth
R
0

In case an interface shall be applied as well:

public class ChildClass<T> : BaseClass where T : class, IInterface
Rinarinaldi answered 7/5, 2024 at 15:54 Comment(0)
J
-1

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

Joliejoliet answered 8/4, 2014 at 14:43 Comment(1)
I am not referring to multiple inherit is just a constrain over the generic type, and.... inherit from other classYearning

© 2022 - 2025 — McMap. All rights reserved.