Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interface Delegation in C#

In Delphi we can delegate the implementation of an interface to another class, I'm wondering if this is possible in C#?

For example, I have the interface IMyInterface and I say TMyClass implements IMyInterface. but actually it doesn't. Internally I can use the implements keyword to delegate the interface implementation to another class without having to declare every method in TMyClass.

like image 857
There is no spoon Avatar asked Jul 05 '12 10:07

There is no spoon


1 Answers

There is a simple answer: no, C# does not allow it in the same way as in Delphi.

For those knowing C# but not Delphi, this is what is meant: http://docwiki.embarcadero.com/RADStudio/en/Implementing_Interfaces , see the "Implementing Interfaces by Delegation (Win32 only)" section.

I guess you will have to pass the method calls to the interface manually. My C# is a litle bit rusty (I can still read it very well, though):

public class Blah : ISomeInterface
{
    public ISomeInterface implementer { getter and setter here }

    public int ISomeInterface.DoThis() 
    { 
        if (implementer) return implementer.DoThis(); 
    }
    public void ISomeInterface.DoThat(int param) 
    { 
        if (implementer) implementer.DoThat(param); 
    }

etc...

Where DoThis and DoThat are methods of ISomeInterface that must be implemented by Blah. In C#, you must explicitly delegate each of these methods to the contained interface. In Delphi, this is done automatically (i.e. the methods are generated and called behind the scenes, invisibly to the user), when you use the implements keyword after a property of a class or interface type.

I assume that some of the answerers are confused by the use of the terms implements and delegation, which have a different meaning in C#.

like image 63
Rudy Velthuis Avatar answered Sep 16 '22 18:09

Rudy Velthuis