473,404 Members | 2,179 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,404 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 52877
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
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

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.