Add an object that does not implement the interface, but meets all qualifications, a list that expects an interface

advertisements

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


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