I have two classes: a base class (BaseClass) and a class deriving from
it (DerivedClass). I have a List<DerivedCla ss> 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.Collect ions.Generic.Li st`1' to
type 'System.Collect ions.Generic.Li st`1'."
Replacing the line "baseClasse s = (List<BaseClass >) temp;" with
"baseClasse s = (List<BaseClass >) derivedClasses" causes the compiler to
show an error:
"Cannot convert type
'System.Collect ions.Generic.Li st<ConsoleAppli cation1.Derived Class>' to
'System.Collect ions.Generic.Li st<ConsoleAppli cation1.BaseCla ss>'"
Is there anyway to accomplish this? Code follows...
using System;
using System.Collecti ons.Generic;
namespace ConsoleApplicat ion1
{
class Program
{
static void Main(string[] args)
{
List<DerivedCla ss> derivedClasses;
List<BaseClass> baseClasses;
object temp;
derivedClasses = new List<DerivedCla ss>();
temp = derivedClasses;
baseClasses = (List<BaseClass >) temp;
}
}
public abstract class BaseClass {}
public abstract class DerivedClass : BaseClass { }
}
it (DerivedClass). I have a List<DerivedCla ss> 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.Collect ions.Generic.Li st`1' to
type 'System.Collect ions.Generic.Li st`1'."
Replacing the line "baseClasse s = (List<BaseClass >) temp;" with
"baseClasse s = (List<BaseClass >) derivedClasses" causes the compiler to
show an error:
"Cannot convert type
'System.Collect ions.Generic.Li st<ConsoleAppli cation1.Derived Class>' to
'System.Collect ions.Generic.Li st<ConsoleAppli cation1.BaseCla ss>'"
Is there anyway to accomplish this? Code follows...
using System;
using System.Collecti ons.Generic;
namespace ConsoleApplicat ion1
{
class Program
{
static void Main(string[] args)
{
List<DerivedCla ss> derivedClasses;
List<BaseClass> baseClasses;
object temp;
derivedClasses = new List<DerivedCla ss>();
temp = derivedClasses;
baseClasses = (List<BaseClass >) temp;
}
}
public abstract class BaseClass {}
public abstract class DerivedClass : BaseClass { }
}
Comment