views:

51

answers:

1

I have a feeling I already know the answer people are going to give, but here goes anyway:

Say I'm writing a new class, let's call it PooledQueue<T>, in the constructor of which I want to accept an argument that implements the interface IResourcePool<T>. The idea here is that I'm fine with using any underlying pool object, as long as it gives me the properties/methods of IResourcePool<T> (you know, the whole idea behind interfaces, right?).

But if there's already a class available that provides all the functionality of IResourcePool<T>, except that it doesn't implement IResourcePool<T> (and I can't modify the source code), is there any way for me to force the implementation?

What I'm expecting people to answer is that I should just make a wrapper for the existing class that does implement the necessary interface. But I'd just prefer to be able to do this:

// GetDataPool returns an object of type Pool<Data> that I can't modify
var q = new PooledQueue<Data>(GetDataPool());

instead of this:

var q = new PooledQueue<Data>(new PoolWrapper<Data>(GetDataPool()));

I guess what I feel would be really useful is if a class's implementation of an interface could be defined separately from the class definition. Sort of the way a well-designed database is structued--with association tables linking entities with IDs from other tables. Does that make sense?

+1  A: 

Out of the box, you cannot force an interface on a class without inheriting from it.

There are ways, such as using a transparent RealProxy or 3rd-party libraries such as LinFU, which allow you to simulate stuff like this, but at a higher cost than making your wrapper class.

In fact, you could make an overload constructor which creates the wrapper for you, so that the code stays clean...

Lucero
+1 - especially like the part with the overloaded constructor.
Fredrik Mörk