-
Notifications
You must be signed in to change notification settings - Fork 4.2k
Closed
Labels
Description
There was useful feature in Borland Delphi, interface delegation. This feature is absent in C#.
You can delegate interface implementation on class to instance stored in field or property.
Declare sample interface and sample implementation:
public interface ISampleInterface
{
void DoSomeWork();
int GetSomeResult();
}
public sealed class SampleImplementation : ISampleInterface
{
public void DoSomeWork()
{
// do some work
}
public int GetSomeResult()
{
// return some result here
}
}Delegate interface implementation:
public sealed class DelegatedImplementation : ISampleInterface
{
private ISampleInterface _wrappedObj : ISampleInterface;
public DelegatedImplementation(ISampleInterface wrappedObj)
{
_wrappedObj = wrappedObj;
}
}This would translate to:
public sealed class DelegatedImplementation : ISampleInterface
{
private ISampleInterface _wrappedObj;
void ISampleInterface.DoSomeWork()
{
_wrappedObj.DoSomeWork();
}
int ISampleInterface.GetSomeResult()
{
return _wrappedObj.GetSomeResult();
}
public DelegatedImplementation(ISampleInterface wrappedObj)
{
_wrappedObj = wrappedObj;
}
}So, ISampleInterface implementation is transparently delegated to field _wrappedObj
private ISampleInterface _wrappedObj : ISampleInterface;Class, of course, can override this behavior:
public sealed class DelegatedImplementation : ISampleInterface
{
private ISampleInterface _wrappedObj : ISampleInterface;
/* delegation for DoSomeWork member is ignored as class explicitly implement this member */
void ISampleInterface.DoSomeWork()
{
// do some other work
}
public DelegatedImplementation(ISampleInterface wrappedObj)
{
_wrappedObj = wrappedObj;
}
}This would translate to:
public sealed class DelegatedImplementation : ISampleInterface
{
private ISampleInterface _wrappedObj;
/* delegation for DoSomeWork member is ignored as class explicitly implement this member */
void ISampleInterface.DoSomeWork()
{
// do some other work
}
/* this member is still delegated as class doesn't override delegation behavior */
int ISampleInterface.GetSomeResult()
{
return _wrappedObj.GetSomeResult();
}
public DelegatedImplementation(ISampleInterface wrappedObj)
{
_wrappedObj = wrappedObj;
}
}AqlaSolutions, VisualMelon, GeorgePetri, yringler, edward-a and 7 more