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

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
 
I

Ignacio Machin ( .NET/ C# MVP )

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.
 
E

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.

Thank you so much Ignacio.

Emilio
 
P

Pavel Minaev

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?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top