M
matty.hall
I have two classes: a base class (BaseClass) and a class deriving from
it (DerivedClass). I have a List<DerivedClass> that for various
reasons needs to be of that type, and not a List<BaseClass>. However, I
need to cast that list to a List<BaseClass> and it is not working. The
code is below. I get the following exception:
"Unable to cast object of type 'System.Collections.Generic.List`1' to
type 'System.Collections.Generic.List`1'."
Replacing the line "baseClasses = (List<BaseClass>) temp;" with
"baseClasses = (List<BaseClass>) derivedClasses" causes the compiler to
show an error:
"Cannot convert type
'System.Collections.Generic.List<ConsoleApplication1.DerivedClass>' to
'System.Collections.Generic.List<ConsoleApplication1.BaseClass>'"
Is there anyway to accomplish this? Code follows...
using System;
using System.Collections.Generic;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List<DerivedClass> derivedClasses;
List<BaseClass> baseClasses;
object temp;
derivedClasses = new List<DerivedClass>();
temp = derivedClasses;
baseClasses = (List<BaseClass>) temp;
}
}
public abstract class BaseClass {}
public abstract class DerivedClass : BaseClass { }
}
it (DerivedClass). I have a List<DerivedClass> that for various
reasons needs to be of that type, and not a List<BaseClass>. However, I
need to cast that list to a List<BaseClass> and it is not working. The
code is below. I get the following exception:
"Unable to cast object of type 'System.Collections.Generic.List`1' to
type 'System.Collections.Generic.List`1'."
Replacing the line "baseClasses = (List<BaseClass>) temp;" with
"baseClasses = (List<BaseClass>) derivedClasses" causes the compiler to
show an error:
"Cannot convert type
'System.Collections.Generic.List<ConsoleApplication1.DerivedClass>' to
'System.Collections.Generic.List<ConsoleApplication1.BaseClass>'"
Is there anyway to accomplish this? Code follows...
using System;
using System.Collections.Generic;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List<DerivedClass> derivedClasses;
List<BaseClass> baseClasses;
object temp;
derivedClasses = new List<DerivedClass>();
temp = derivedClasses;
baseClasses = (List<BaseClass>) temp;
}
}
public abstract class BaseClass {}
public abstract class DerivedClass : BaseClass { }
}