user1899020
user1899020

Reputation: 13575

How to declare a generic method with a generic collection?

For example

void f<C, T>(C<T> collection, T element) : where C has member method BindarySearch

I have two questions:

  1. If it is possible to declare a generic method with a generic collection? If so, how?
  2. How to make C has a particular member method? Thanks.

Upvotes: 0

Views: 77

Answers (1)

James Buck
James Buck

Reputation: 1640

You can use an interface to enforce the required members:

interface IHasBinarySearch<T> : ICollection<T> {
    int BinarySearch(T item);
}

Then a generic method can be defined like so:

void f<C, T>(C collection, T element) where C : IHasBinarySearch<T>

This interface is already a generic collection (by extending ICollection<T>) so no need to specify the constraint on the method again.

Upvotes: 1

Related Questions