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.
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#.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With