Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cast a list of derived types when casting the parent derived class to it's base type

I have simplified the code for brevity.

There are two base classes, Document and Line and two classes derived from those, DocumentPlus and LinePlus.

Document and DocumentPlus contain a List<Line> and List<LinePlus> respectively.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

public class Test
{

    public class Document
    {
        public List<Line> Lines = new List<Line>();
    }

    public class Line
    {
        public string? A;
    }

    public class DocumentPlus : Document
    {
        public new List<LinePlus> Lines = new List<LinePlus>();
    }

    public class LinePlus : Line
    {
        public string? B;
    }
        
    public Test()
    {
        var x = new DocumentPlus();
        x.Lines = new List<LinePlus>()
        {
            new LinePlus() { A = "123", B = "456" },
            new LinePlus() { A = "789", B = "101" },
            new LinePlus() { A = "112", B = "131" }
        };

        var y = (Document)x;

        var z = y.Lines;
        // Z should be the Lines entered above but as their base type
        // Just not sure how to do it!

    }

}

Is there any way I can cast the List<LinePlus> to List<Line> when casting a DocumentPlus instance to Document?

Thanks!

>Solution :

Try this.

using System.Linq

public Document CastDocPlusToDoc(DocumentPlus inputDocP) {
    Document outputDoc = new Document();
    outputDoc.Lines.AddRange(inputDocP.LinesPlus.Cast<Lines>());
}

var y = CastDocPlusToDoc(x)

I’m not even sure that .Cast is necessary here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading