Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add object which does not implement interface, but meets all qualifications, to a list expecting interface

I have the following:

List<IReport> myList = new List<IReport>();

Report myReport = TheirApi.GetReport();

myReport meets all the qualifications of IReport, but cannot implement IReport because I do not have access to the source of TheirApi. Casting to type IReport obviously results in null, and I read that I cannot cast an anonymous type to an interface.

Do I have any options here?

A wrapper class was just what the doctor ordered:

ReportServices.GetAllCustomReports().ToList().ForEach(customReport => _customReports.Add(new ReportWrapper(customReport)));

public class ReportWrapper : IReport
{
    private Report inner;

    public int ID 
    {
        get { return inner.ID;  }
        set { inner.ID = value; }
    }
    public string Name
    {
        get { return inner.Name; }
        set { inner.Name = value; }
    }

    public ReportWrapper(Report obj)
    {
        inner = obj;
    }
}
like image 914
Sean Anderson Avatar asked Nov 27 '25 13:11

Sean Anderson


2 Answers

You will need to wrap this object inside another one that implements the interface, and then you will need to implement it calling the inner object's properties and methods.

For example:

public class ReportWrapper : IReport
{
    MyObjectIsLikeReport inner;

    public ReportWrapper(MyObjectIsLikeReport obj) {
        this.inner = obj;
    }

    public void ReportMethod(int value) {
        this.inner.ReportMethod(value);
    }

    public int SomeProperty {
        get { return this.inner.SomeProperty; }
        set { this.inner.SomeProperty = value; }
    }
}

To use it, you can do this:

List<IReport> myList = new List<IReport>();
MyObjectIsLikeReport myReport = TheirApi.GetReport();
myList.Add(new ReportWrapper(myReport));
like image 158
Miguel Angelo Avatar answered Nov 29 '25 06:11

Miguel Angelo


Consider Adapter Design Pattern.

Definition: Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.

good reference: http://www.dofactory.com/Patterns/PatternAdapter.aspx

interface IReport
{
    void DoSomething();
}

class ReportApdapter : IReport
{
    private readonly Report _report;

    public ReportApdapter(Report report)
    {
        _report = report;
    }

    public void DoSomething()
    {
        _report.DoSomething();
    }
}

class Report
{
    public void DoSomething()
    {
    }
}


//You can use like this.
IReport report = new ReportApdapter(TheirApi.GetReport());
like image 23
Jin-Wook Chung Avatar answered Nov 29 '25 04:11

Jin-Wook Chung



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!