Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I make a .NET framework class implement an interface that I define?

Tags:

.net

interface

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
like image 674
skb Avatar asked Feb 24 '26 09:02

skb


2 Answers

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.

like image 156
Neil Barnwell Avatar answered Feb 25 '26 23:02

Neil Barnwell


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.

like image 40
Marc Gravell Avatar answered Feb 25 '26 23:02

Marc Gravell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!