Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to make a parameter implement two interfaces?

Tags:

Is it possible to define a function that takes in a parameter that must implement two interfaces?

(The two interfaces are ones I just remembered off the top of my head; not the ones I want to use)

private void DoSomthing(IComparable, ICollection input) {  } 
like image 958
Pondidum Avatar asked Apr 21 '09 10:04

Pondidum


People also ask

Can you implement 2 interfaces?

A class can implement more than one interface at a time. A class can extend only one class, but implement many interfaces. An interface can extend another interface, in a similar way as a class can extend another class.

What happens if a class implement 2 interfaces having same method?

A class implementation of a method takes precedence over a default method. So, if the class already has the same method as an Interface, then the default method from the implemented Interface does not take effect. However, if two interfaces implement the same default method, then there is a conflict.

How many interfaces we can implement?

But if you really really want to know the theoretical maximum number of interfaces a class can implement, it's 65535.


2 Answers

You can:

1) Define an interface that inherits both required interfaces:

public interface ICombinedInterface : IComparable, ICollection {... }  private void DoSomething(ICombinedInterface input) {... } 

2) Use generics:

private void DoSomething<T>(T input)     where T : IComparable, ICollection {...} 
like image 94
Kent Boogaart Avatar answered Jan 03 '23 12:01

Kent Boogaart


You can inherit another interface from those two interfaces and make your parameter implement that interface.

like image 29
Steve Willcock Avatar answered Jan 03 '23 12:01

Steve Willcock