tags:

views:

253

answers:

3

I want to take a .NET class (let's say FileInfo for the sake of discussion) and have it implement my interface. For example:

public interface IDeletable
{
    void Delete();
}

Note that the FileInfo DOES have the Delete() method, so this interface could make sense.

So that I can have code like this:

FileInfo fileinfo = ...;
DeletObject(fileInfo);

public void DeleteObject(IDeletable deletable)
{
    deletable.Delete();
}

Is it possible to make an existing class match an interface like this?

  • Sean
+5  A: 

Nope. You need the Adapter pattern. This gives you a class that implements the interface you want, and "adapts" the framework class interface for you. This means your interface design doesn't even necessarily have to exactly match the framework class's interface.

As Marc Gravell points out in another answer, you might be able to cheat and use extension methods.

Neil Barnwell
+2  A: 

You can't, basically. Not for Delete (since it already exists), but in general: one option with C# 3.0 is extension methods:

public static void SomeMethod(this FileInfo file)
{ ... your code ... }

Now you can use:

FileInfo file = ...
file.SomeMethod();

But there is no interface here.

Marc Gravell
+1  A: 

As @Neil Barnwell said, Adapter is the way to go. But beware, interfaces are not supposed to be used that way, and though it may come in handy, you should at least think carefully about it.

See, interface are not bijective functions, they are intended to provide a set of "rules" defining what an object is capable of doing yes, but the order in which they are supposed to use them is by first defining them to describe your application design (or what ever you need) and then use it, not the other way around. Or in other words, the interface defines a behavior in the context of YOUR application, that might or might not, collide with the intended use the .NET framework was intended.

That means, for every class you "adapt" you have to make sure not only that it follows the syntax of the interface (same method name, same parameters) but also that it follows the spirit of the interface.

For example, I can have a class with a Dispose method... that doesn't necessarily mean it implements IDisposable ... maybe it doesn't because my Dispose method can raise an exception, or block for a given time, so while fulfilling the contract it doesn't fulfill the spirit.

Now, that can happen in your application as well, but is much less likely to happen because you know the interface, so it's only natural you adhere to its spirit... but how could the .NET framework developer do the same?

Jorge Córdoba