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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With