Skip to content

Proposal: C# interface delegation #13952

@Opiumtm

Description

@Opiumtm

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;
    }
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions