Can an Interface be implemented only by a particular type of class?

  • Thread starter Thread starter Emilio
  • Start date Start date
E

Emilio

Good evening to everyone

as the subject says,

can an Interface be implemented only by a particular type of class
(for example by a "Car" class).

Best regards,
Emilio
 
Good evening to everyone

as the subject says,

can an Interface be implemented only by a particular type of class
(for example by a "Car" class).

Best regards,
Emilio

Hi,

No, any class can implement an interface. Of course if the class has
access to the interface. For example, if an interface is declared as
internal no class outside the assembly can implement it but ANY class
in the assembly can.
 
Hi,

No, any class can implement an interface. Of course if the class has
access to the interface. For example, if an interface is declared as
internal no class outside the assembly can implement it but ANY class
in the assembly can.

Thank you so much Ignacio.

Emilio
 
Good evening to everyone

as the subject says,

can an Interface be implemented only by a particular type of class
(for example by a "Car" class).

There are some hacks with generics, technically... for example:

interface IFoo<T> where T : Car, IFoo<T> { ... }

Now a class C can implement IFoo<C> only if it's derived from Car.

In practice, this is rather pointless, because you really get a family
of interfaces here, with distinct one for each T - so you cannot use
them for polymorphism. Furthermore, the original idea (interface
that's only implemented by a single class) has the same flaw -
interfaces enable polymorphism, and using them for one class defeats
that purpose, so why would you even want to do that?
 
Back
Top