Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easiest way of casting List<Descendant> to List<Base>

I have a class structure like this:

abstract class Base{}
class Descendant : Base{}

I have another class that needs a list of type List<Base>. I know I can just add Descendant instances to a List<Base> but I'd think it'd be preferable to keep stronger-typing here.

What is the easiest way of casting from List<Descendant> to List<Base>?

like image 655
Earlz Avatar asked Nov 29 '25 21:11

Earlz


1 Answers

Use LINQ:

List<Descendant> descendants = ...;

descendants.Cast<Base>().ToList();
like image 126
coding4beer Avatar answered Dec 01 '25 11:12

coding4beer



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!