473,231 Members | 1,674 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,231 software developers and data experts.

Casting List<> of derived class to List<> of base class?

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<ConsoleApplicatio n1.DerivedClass>' to
'System.Collections.Generic.List<ConsoleApplicatio n1.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 { }
}

Nov 17 '05 #1
4 52786
One more thing...

I do know about List<>.ConvertAll. However, I can't use this because
the type of the Derived class is not known at compile time (i.e. there
will be DerivedClassOne, DerivedClassTwo, etc and we don't know which
one it is because this conversion is actually happening in the base
class, which isn't a fact show in the code above, which I omitted to
keep the pasted code short).

The problem is that doing doing ConvertAll() with a Converter declared
as Converter<BaseClass, BaseClass> throws a compile time error "The
type arguments for method
'System.Collections.Generic.List<ConsoleApplicatio n1.DerivedClass>.ConvertAll<TOutput>(System.Conver ter<ConsoleApplication1.DerivedClass,TOutput>)'
cannot be inferred from the usage. Try specifying the type arguments
explicitly."

Alternatively, at runtime I know the type of the derived class from
GetType(). However, I don't know how (or if it is even possible) to
declare a generic type using runtime type information (i.e. something
like Converter<this.GetType(), BaseClass>).

Any thoughts?

Nov 17 '05 #2
<ma********@gmail.com> wrote:
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<ConsoleApplicatio n1.DerivedClass>' to
'System.Collections.Generic.List<ConsoleApplicatio n1.BaseClass>'"

Is there anyway to accomplish this? Code follows...


No. List<DerivedClass> isn't derived from List<BaseClass>. If it were,
you'd be able to do:

List<String> x = new List<String>();
List<Object> y = x;

y.Add (new Object()); // Bang! x is only meant to contain strings...

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #3
FWIW, this is what actually works:

using System;
using System.Collections.Generic;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List<DerivedClass> derivedClasses;
BaseClass[] baseClasses;

derivedClasses = new List<DerivedClass>();
baseClasses = derivedClasses.ToArray();
}
}

public abstract class BaseClass { }
public class DerivedClass : BaseClass { }
}

Nov 17 '05 #4
Yes, that works, but the problem that Jon points out still exists. If
you tried to take baseClasses and populate a List<DerivedClass> with it, it
could fail at runtime. This is the risk you run if you have to go the other
way.

--
- Nicholas Paldino [.NET/C# MVP]
- ca*******@caspershouse.com

<ma********@gmail.com> wrote in message
news:11**********************@f14g2000cwb.googlegr oups.com...
FWIW, this is what actually works:

using System;
using System.Collections.Generic;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List<DerivedClass> derivedClasses;
BaseClass[] baseClasses;

derivedClasses = new List<DerivedClass>();
baseClasses = derivedClasses.ToArray();
}
}

public abstract class BaseClass { }
public class DerivedClass : BaseClass { }
}

Nov 17 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: tirath | last post by:
Hi all, I have a templated class that derives from a non-templated abstract class. How do I then cast a base class pointer to a <templated> derived class pointer in a generalised fashion? ...
3
by: H. S. | last post by:
Hi, I am trying to compile these set of C++ files and trying out class inheritence and function pointers. Can anybody shed some light why my compiler is not compiling them and where I am going...
20
by: Anonymous | last post by:
Is there a non-brute force method of doing this? transform() looked likely but had no predefined function object. std::vector<double> src; std::vector<int> dest; ...
2
by: phl | last post by:
Hi, I have a base class which inherits List<T>, how do I iterate this class from the calling class? Do I have to use enumerater? Does anyone have any code samples? Thx phl base class:
6
by: buzzweetman | last post by:
Many times I have a Dictionary<string, SomeTypeand need to get the list of keys out of it as a List<string>, to pass to a another method that expects a List<string>. I often do the following: ...
3
by: janzon | last post by:
Hi! Sorry for the bad subject line... Here's what I mean. Suppose we deal with C++ standard integers lists (the type is indifferent). We have a function f, declared as list<intf(int); Now...
2
by: per9000 | last post by:
Hi, *background* I want a class containing an int (a list of sets of integer). This should be hidden for the user and he/she should be able to insert his/her favourite data structure so to be a...
0
by: Weeble | last post by:
On Jun 20, 11:10 pm, Göran Andersson <gu...@guffa.comwrote: I did it that way because CopyTo has a whole bunch of failure cases to take care of (multi-dimensional array, not enough space,...
36
by: puzzlecracker | last post by:
Would someone explain why this declaration is illegal: class Sample<T> where T : Stream, class
3
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 3 Jan 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). For other local times, please check World Time Buddy In...
0
by: jianzs | last post by:
Introduction Cloud-native applications are conventionally identified as those designed and nurtured on cloud infrastructure. Such applications, rooted in cloud technologies, skillfully benefit from...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: fareedcanada | last post by:
Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16,17 and if 11314151617 (11cnt) then should be split like...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.