473,408 Members | 1,700 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,408 software developers and data experts.

Casting of generics?

Hi all!

I have a problem of casting generics to their base type. In the code
below I first define a BaseList class that can hold items of any type
that inherits from BaseItem. I then define a DerivedList that can hold
items of the type DerivedItem, which inherits from BaseList.
So far so good... But if I somehow get an object that I know is a
subclass of BaseList (and therefor holds subclasses of BaseItem) and
try to cast it to BaseList<BaseItemi get an InvalidCastException
(also below).
Because both the list class and the item class(es) it contains can be
cast to their base classes I think that the whole should also be
castable? Or am I wrong? Is this an syntactic error or a thought fault?
=)

Regards,
Richard

Code (can also be found at http://pastebin.com/866977 )

class BaseItem {
}

class DerivedItem : BaseItem {
}

class BaseList<Twhere T : BaseItem {
}

class DerivedList : BaseList<DerivedItem{
}

class Program {
static void Main(string[] args) {
// Suppose i get this value (dl) from outside as an object.
// I only know that it is a subclass of BaseList and it is
// parameterized with some subclass of BaseItem
DerivedList dl = new DerivedList();
object o = dl;

// This cast fails!
BaseList<BaseItemdl2 = (BaseList<BaseItem>) o;
}
}

Exception:

System.InvalidCastException was unhandled
Message="Unable to cast object of type 'TestConsoleApp.DerivedList'
to type 'TestConsoleApp.BaseList`1[TestConsoleApp.BaseItem]'."
Source="TestConsoleApp"
StackTrace:
at TestConsoleApp.Program.Main(String[] args) in Program.cs:line
28
at System.AppDomain.nExecuteAssembly(Assembly assembly, String[]
args)
at System.AppDomain.ExecuteAssembly(String assemblyFile,
Evidence assemblySecurity, String[] args)
at
Microsoft.VisualStudio.HostingProcess.HostProc.Run UsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context( Object
state)
at System.Threading.ExecutionContext.Run(ExecutionCon text
executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()

Jan 25 '07 #1
3 1794
You can't, I remembered a post on the same(ish, it's the same concept)
topic a while ago which can be found here (Watch wrap)--->

http://groups.google.co.uk/group/mic...77888d00f45e93

On 25 Jan, 13:25, "psyCK0" <nasseg...@gmail.comwrote:
Hi all!

I have a problem of casting generics to their base type. In the code
below I first define a BaseList class that can hold items of any type
that inherits from BaseItem. I then define a DerivedList that can hold
items of the type DerivedItem, which inherits from BaseList.
So far so good... But if I somehow get an object that I know is a
subclass of BaseList (and therefor holds subclasses of BaseItem) and
try to cast it to BaseList<BaseItemi get an InvalidCastException
(also below).
Because both the list class and the item class(es) it contains can be
cast to their base classes I think that the whole should also be
castable? Or am I wrong? Is this an syntactic error or a thought fault?
=)

Regards,
Richard

Code (can also be found athttp://pastebin.com/866977)

class BaseItem {

}class DerivedItem : BaseItem {

}class BaseList<Twhere T : BaseItem {

}class DerivedList : BaseList<DerivedItem{

}class Program {
static void Main(string[] args) {
// Suppose i get this value (dl) from outside as an object.
// I only know that it is a subclass of BaseList and it is
// parameterized with some subclass of BaseItem
DerivedList dl = new DerivedList();
object o = dl;

// This cast fails!
BaseList<BaseItemdl2 = (BaseList<BaseItem>) o;
}

}Exception:

System.InvalidCastException was unhandled
Message="Unable to cast object of type 'TestConsoleApp.DerivedList'
to type 'TestConsoleApp.BaseList`1[TestConsoleApp.BaseItem]'."
Source="TestConsoleApp"
StackTrace:
at TestConsoleApp.Program.Main(String[] args) in Program.cs:line
28
at System.AppDomain.nExecuteAssembly(Assembly assembly, String[]
args)
at System.AppDomain.ExecuteAssembly(String assemblyFile,
Evidence assemblySecurity, String[] args)
at
Microsoft.VisualStudio.HostingProcess.HostProc.Run UsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context( Object
state)
at System.Threading.ExecutionContext.Run(ExecutionCon text
executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
Jan 25 '07 #2
Remember that Generics allow you to create strong data types, and treat them
as such. So,

DerivedList : BaseList<DerivedItem>

is a strongly-typed BaseList, of type DerivedItem.

However, you are attempting to cast it to:

BaseList<BaseItem>

which is a strongly-typed BaseList of type BaseItem.

Now, if you were to cast it as

BaseList<DerivedItem>

which is the type it inherits, the cast would not fail.
BaseList<DerivedItemdoes not inherit BaseList<BaseItem>.

--
HTH,

Kevin Spencer
Microsoft MVP
Software Composer
http://unclechutney.blogspot.com

The shortest distance between 2 points is a curve.
"psyCK0" <na*******@gmail.comwrote in message
news:11*********************@q2g2000cwa.googlegrou ps.com...
Hi all!

I have a problem of casting generics to their base type. In the code
below I first define a BaseList class that can hold items of any type
that inherits from BaseItem. I then define a DerivedList that can hold
items of the type DerivedItem, which inherits from BaseList.
So far so good... But if I somehow get an object that I know is a
subclass of BaseList (and therefor holds subclasses of BaseItem) and
try to cast it to BaseList<BaseItemi get an InvalidCastException
(also below).
Because both the list class and the item class(es) it contains can be
cast to their base classes I think that the whole should also be
castable? Or am I wrong? Is this an syntactic error or a thought fault?
=)

Regards,
Richard

Code (can also be found at http://pastebin.com/866977 )

class BaseItem {
}

class DerivedItem : BaseItem {
}

class BaseList<Twhere T : BaseItem {
}

class DerivedList : BaseList<DerivedItem{
}

class Program {
static void Main(string[] args) {
// Suppose i get this value (dl) from outside as an object.
// I only know that it is a subclass of BaseList and it is
// parameterized with some subclass of BaseItem
DerivedList dl = new DerivedList();
object o = dl;

// This cast fails!
BaseList<BaseItemdl2 = (BaseList<BaseItem>) o;
}
}

Exception:

System.InvalidCastException was unhandled
Message="Unable to cast object of type 'TestConsoleApp.DerivedList'
to type 'TestConsoleApp.BaseList`1[TestConsoleApp.BaseItem]'."
Source="TestConsoleApp"
StackTrace:
at TestConsoleApp.Program.Main(String[] args) in Program.cs:line
28
at System.AppDomain.nExecuteAssembly(Assembly assembly, String[]
args)
at System.AppDomain.ExecuteAssembly(String assemblyFile,
Evidence assemblySecurity, String[] args)
at
Microsoft.VisualStudio.HostingProcess.HostProc.Run UsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context( Object
state)
at System.Threading.ExecutionContext.Run(ExecutionCon text
executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()

Jan 25 '07 #3


On Jan 25, 5:25 am, "psyCK0" <nasseg...@gmail.comwrote:
Hi all!

I have a problem of casting generics to their base type. In the code
below I first define a BaseList class that can hold items of any type
that inherits from BaseItem. I then define a DerivedList that can hold
items of the type DerivedItem, which inherits from BaseList.
So far so good... But if I somehow get an object that I know is a
subclass of BaseList (and therefor holds subclasses of BaseItem) and
try to cast it to BaseList<BaseItemi get an InvalidCastException
(also below).
Because both the list class and the item class(es) it contains can be
cast to their base classes I think that the whole should also be
castable? Or am I wrong? Is this an syntactic error or a thought fault?
=)
It's a "thought fault". Think about it for a moment: if you could cast
a BaseList<DerivedItemto a reference variable for a
BaseList<BaseItem>, then you could add BaseItems to the list, which
clearly violates the constraint that the list is of DerivedItems. For
example:

BaseList<FiremanfireList = new BaseList<Fireman>();
BaseList<PersonpersonList = (BaseList<Person>)fireList;
personList.Add(new ComputerProgrammer());

If the second line were allowed, then the third line could not be
checked at compile time, which would incur a run-time cost (type
checking) for all operations on generics, which is precisely what
generics seek to avoid.

Generics make strong guarantees that can be verified at compile time,
and so need no run-time type checking.

Jan 25 '07 #4

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

Similar topics

4
by: c | last post by:
Hello All, I am struggling with simple casting issue within c# and would really appreciate some insight into where I am going wrong. I have two classes, ClassA and ClassB. Each implements a...
7
by: yufufi | last post by:
lets say we have a 'shape' class which doesn't implement IComparable interface.. compiler doesn't give you error for the lines below.. shape b= new shape(); IComparable h; h=(IComparable)b;...
4
by: KC | last post by:
Could some one explain to me the casting rules for sending generic lists, ex. List<Person>, to a function that accepts List<object>? I cannot get the following easy-cheesy app to work. I get the...
4
by: krahenbuhl | last post by:
Dear All, I've a question related to Generics and casting in c# 2.0. I've a class called Client which implements interface IClient. I'd like to do: LinkedList<Client> clients; public...
5
by: anders.forsgren | last post by:
This is a common problem with generics, but I hope someone has found the best way of solving it. I have these classes: "Fruit" which is a baseclass, and "Apple" which is derived. Further I have...
8
by: Kris Jennings | last post by:
Hi, I am trying to create a new generic class and am having trouble casting a generic type to a specific type. For example, public class MyClass<Twhere T : MyItemClass, new() { public...
3
by: Tigger | last post by:
I have an object which could be compared to a DataTable/List which I am trying to genericify. I've spent about a day so far in refactoring and in the process gone through some hoops and hit some...
7
by: Ajeet | last post by:
hi I am having some difficulty in casting using generics. These are the classes. public interface IProvider<PROF> where PROF : IProviderProfile { //Some properties/methods }
3
by: =?Utf-8?B?TWlydHVs?= | last post by:
Hi I'm currently working with vbscripting through MSScriptControl. We have shared some of our objects that should be available for scripting. Some of the functions of these objects will return...
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
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
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
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,...
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
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...

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.