Reputation: 61
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?
Upvotes: 3
Views: 2066
Reputation: 31
If the implementation is always the same then you could use something like this:
class Fubar : IFubar {
public void SomeIFubarMethod() { … }
}
class Foo : Fubar { … }
class Baz : Fubar { … }
Then you can use the same inheritance for Bar
and Qux
(and you don't even need to specify the IFubar
interface again):
class Bar : Foo { … }
class Qux : Baz { … }
Upvotes: 0
Reputation: 1063338
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)
Upvotes: 5