473,703 Members | 2,912 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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<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 { }
}

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

I do know about List<>.ConvertA ll. 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<BaseC lass, BaseClass> throws a compile time error "The
type arguments for method
'System.Collect ions.Generic.Li st<ConsoleAppli cation1.Derived Class>.ConvertA ll<TOutput>(Sys tem.Converter<C onsoleApplicati on1.DerivedClas s,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********@gma il.com> wrote:
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...


No. List<DerivedCla ss> 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.co m>
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.Collecti ons.Generic;

namespace ConsoleApplicat ion1
{
class Program
{
static void Main(string[] args)
{
List<DerivedCla ss> derivedClasses;
BaseClass[] baseClasses;

derivedClasses = new List<DerivedCla ss>();
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<DerivedCla ss> 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*******@caspe rshouse.com

<ma********@gma il.com> wrote in message
news:11******** **************@ f14g2000cwb.goo glegroups.com.. .
FWIW, this is what actually works:

using System;
using System.Collecti ons.Generic;

namespace ConsoleApplicat ion1
{
class Program
{
static void Main(string[] args)
{
List<DerivedCla ss> derivedClasses;
BaseClass[] baseClasses;

derivedClasses = new List<DerivedCla ss>();
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
6574
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? Here's what I'm generally trying to achieve: I'm building (trying to anyway) a serialization library. Here's my design:
3
2474
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 wrong? I am using g++ (GCC) 3.3.5 on a Debian Sarge system. The compiler complains: //**************************** //**************************** Compiler output starts *********** cd /home/red/tmp/testprogs/
20
17820
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; std::vector<double>::size_type size = src.size(); dest.reserve(size); for (std::vector<int>::size_type i = 0;
2
1695
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
46185
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: <BEGIN CODE> List<stringkeyNameList = new List<string>(); foreach (string keyName in this.myDictionary.Keys)
3
2126
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 we have an integer list p, say. For each element x in p, we want to repace x with f(x) to get a new, possibly larger, integer list. Note
2
2249
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 little fancy I thought I'd do a Ctor like this: // this is the "core": private int sets;
0
278
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, negative index, null array), and I didn't think it was likely to get used that much, so I wanted to do something that would behave correctly without a lot of work. If it became a performance issue I would certainly have changed it later.
36
4539
by: puzzlecracker | last post by:
Would someone explain why this declaration is illegal: class Sample<T> where T : Stream, class
0
8750
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8662
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8961
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7853
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5922
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4679
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3114
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2439
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2058
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.