Workaround for the impossibility of entering code into interfaces

Let's say I have an interface that implements many different classes:

public interface IHaveObjects
{
    object firstObject();
}

(Note: I cannot make it an abstract base class, as IHaveObjects developers may already have a base class.)

Now I want to add a new method to the interface, so that one interface developer may have a special behavior for it. Ideally, I would do something like this:

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

then go to this one of the interface developers and give it an override:

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

However, in C # it is forbidden to provide the body of the method in the interface, and I would like to avoid switching to each executor IHaveObjectsin order to refuse the definition firstObjectOrFallback(). (Imagine if there are hundreds or thousands)

Is there a way to do this without a lot of copies?

+5
3

, IHaveObjects.

, .

:

  interface I1
    {
        void Method1();
    }

    interface I2 : I1
    {
        void Method2();
    }
+2

- , - .

- , C# - .

, - ? extension method ( , , )?

, - , , (IHaveObjectsAndSupportDefault : IHaveObjects) , (, ).

+2

Perhaps I misunderstood your question, but why not use the second interface, for example:

public interface IHaveObjectsEnhanced
{

    object FirstObjectOrFallback();
}

Then you can implement the first and second interface:

public class ObjectHaverPlus : IHaveObjects, IHaveObjectsEnhanced
{

    public object FirstObject()
    {

    }

    public object FirstObjectOrFallback()
    {
         return FirstObject() ?? GetDefault();
    }

}
+1
source

All Articles