Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to define a "shared" method for C# interfaces?

Say I have 4 classes: Foo, Bar, Qux, and Baz. I also have an interface IFubar.

The classes inherit from one another like so:

Bar : Foo, IFubar

Qux : Baz, IFubar

The methods in IFubar will almost always be implemented the same way, no matter what class is inheriting them. The ideal solution would be to have the implementation in IFubar itself, but I can't change IFubar to a class because Bar and Qux have to inherit from Foo and Baz, respectively, and C# doesn't support multiple inheritance.

Is there an easy way to have some sort of "default" logic in an interface, for lack of a better term? Right now my "implementation" is just a call to a static method in another class, which allows me to perform all my logic there and minimize code duplication. I feel like that's not an elegant solution, however.

Ideally, I'd like to have a class derive from some class and IFubar and have it automatically get the same IFubar implementation without me having to copy and paste. I'm fairly certain that sort of thing isn't possible with C#, but I want to make sure.

Honestly, it's nothing more than a mild annoyance that I have to copy and paste the same code over and over again, but I've been trying to think of a more elegant solution and I can't.

This would all be for something used in the Unity3D engine, so I'm limited to things in .NET 3.5, mostly.

Does anyone have any better solutions or suggestions?

like image 268
Jay2645 Avatar asked Dec 05 '25 08:12

Jay2645


1 Answers

The "almost always" is the problem. If it was "always", then an "extension method" would be ideal:

public static class FubarExtensions
{
    public static void SomeMethod(this IFubar obj) { ... }
}

If you need the "almost", they you probably need polymorphism for it to be reliable. In that case, using a static method for the default implementation is probably your best option, i.e.

IFubar.SomeMethod(...)
{
    Fubar.SomeMethodDefault(this, ...);
}

or:

public virtual void SomeMethod(...)
{
    Fubar.SomeMethodDefault(this, ...);
}

(or any similar combination)

like image 192
Marc Gravell Avatar answered Dec 07 '25 22:12

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!