Reputation: 2259
I want to project info from a list of base-class instances into a list of derived-class instances, but I keep running into casting exceptions. Here's an example of what I'm trying to do... how do I make it work?
The following code is up at http://ideone.com/CaXQS , if that helps... thanks in advance!
using System;
using System.Collections.Generic;
namespace AddingReversedNumbers
{
public class MyDerivedClass : MyBaseClass, IMyInterface
{
public int InterfaceProperty { get; set; }
public int DerivedClassProperty { get; set; }
public List<int> DerivedClassList { get; set; }
}
public class MyBaseClass
{
public int BaseClassProperty { get; set; }
}
public interface IMyInterface
{
int InterfaceProperty { get; set; }
}
class Program
{
static void Main()
{
//// This code works just fine.
//var derivedList = new List<MyDerivedClass>();
//derivedList.Add(new MyDerivedClass { BaseClassProperty = 10, DerivedClassProperty = 20, InterfaceProperty = 30 });
//derivedList.Add(new MyDerivedClass { BaseClassProperty = 20, DerivedClassProperty = 40, InterfaceProperty = 60 });
//var baseList = derivedList.ConvertAll(x => (MyBaseClass)x);
// This code breaks when ConvertAll() is called.
var baseList = new List<MyBaseClass>();
baseList.Add(new MyBaseClass{ BaseClassProperty = 10 });
baseList.Add(new MyBaseClass{ BaseClassProperty = 20 });
var derivedList = baseList.ConvertAll(x => (MyDerivedClass)x);
}
}
}
Upvotes: 0
Views: 1638
Reputation: 1500515
In your ConvertAll
code you're just casting. You can't cast a base class instance to a derived class instance. For example, what would you expect casting object
to FileStream
to do? Which file would it refer to?
If you want to create a new object in the ConvertAll
projection, just do that:
var derivedList = baseList.ConvertAll
(x => new MyDerivedClass { BaseClassProperty = x.BaseClassProperty });
Upvotes: 5