Can I indicate that a parameter of type C # should only be an interface?

I would like to implement a C # common class that looks something like this:

abstract class Foobar<T> : AbstractBase, T { ... } 

This is not the case, because C # will allow types after the base class is an interface, so next time I will try:

 abstract class Foobar<T> : AbstractBase, T where T : interface { ... } 

But then I discovered that C # does not allow this form of type restriction. Only where T : struct and where T : class allowed.

How can I say that a type parameter should only be an interface?

+7
generics c # type-constraints
source share
5 answers

Basically, you cannot.

You can bind to a specific interface, but not common to all interfaces. This way you can restrict IEnumerable, for example, but not the interface.

Why do you need this?

+6
source share

The real problem with this code is that you are inheriting from a type parameter.

Attempt to compile

 abstract class Foobar<T> : T { ... } 

will still fail: error CS0689: cannot be obtained from "T" because it is a type parameter.

I think that it would be quite reasonable, at least in the case of abstract classes, and I also wanted this function, but the C # compiler simply will not allow you to do this.

+4
source share

You cannot in simple words.

+1
source share

I believe that you misunderstood the meaning of where T : struct and where T : class .

A general type constraint , as this means that T must be a type value or a reference type, respectively.

However, the purpose of the interface is to define a contract , which is a completely different concept compared to the semantics of the value type and the semantics of the reference type.

Therefore, a restriction like where T : interface does not make sense.

If you want to know more, I suggest you read the C # Programming Guide for restrictions like:

Type Limitations (C # Programming Guide)

+1
source share

This is not so, because C # will allow types after the base class is an interface

This limitation is due to the lack of multiple inheritance in C #. Multiple inheritance can be approximated using interfaces, since overriding methods are explicit. Similarly, a class can extend only one class, but it can implement several interfaces. The trick here is that the implementation class MUST define the body for the method, so the implementation is specific to which method is invoked.

Using the restriction parameter T can be applied to one class or to several interfaces. You cannot limit the range to several classes.

0
source share

All Articles