Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Workaround for being unable to put code in interfaces

Tags:

c#

interface

Let's say I have an interface that many many distinct classes implement:

public interface IHaveObjects
{
    object firstObject();
}

(Note: I can't make it an abstract base class as implementors of IHaveObjects may already have a base class.)

Now I want to add a new method to the interface, so that one implementer of the interface can have special behaviour for it. Ideally I would do something like this:

public interface IHaveObjects
{
    object firstObject();
    object firstObjectOrFallback()
    {
        return firstObject();
    }
}

then go to that one implementor of the interface and give it the override:

public class ObjectHaverPlus : IHaveObjects
{
    public override object IHaveObjects.firstObjectOrFallback()
    {
        return firstObject() ?? getDefault();
    }
}

However it is forbidden in C# to provide a method body in an interface, and I would like to avoid going to every single implementer of IHaveObjects to drop in a definition of firstObjectOrFallback(). (Imagine if there are hundreds or thousands)

Is there a way to do this without lots of copy paste?

like image 616
Patashu Avatar asked Apr 17 '13 05:04

Patashu


2 Answers

How about introducing a second interface which inherits from IHaveObjects.

Than you only have to change these classes, which need the new interface with the new method.

This looks like:

  interface I1
    {
        void Method1();
    }

    interface I2 : I1
    {
        void Method2();
    }
like image 77
Tomtom Avatar answered Sep 25 '22 23:09

Tomtom


That's the problem with interfaces - they don't have any default implementation so any changes to them are breaking changes - i.e. code needs to be modified to work with new version of interface.

Since your implementations already have base classes on their own - you cannot turn it into abstract class, nor does C# have multiple class inheritance.

What you can do is to think - is it really a method on interface? Or could it be implemented as an extension method on interface (didn't try that but I suppose it will work just fine)?

If it is a method on interface and it should stay there - you may think of breaking this interface into two parts, second inheriting from the first (IHaveObjectsAndSupportDefault : IHaveObjects) and use this interface where default value is truly needed (like some other answers indicate).

like image 23
Jarek Avatar answered Sep 25 '22 23:09

Jarek