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.
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