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

how can I cast List<MyObject> to ICollection<IMyObject>

Why can't I cast List<MyObject> to ICollection<IMyObject>.

MyObject implements IMyObject, and of course, List implements
ICollection.

Thanks

Apr 14 '06 #1
5 21631
Jimp <Ja***********@hotmail.com> wrote:
Why can't I cast List<MyObject> to ICollection<IMyObject>.

MyObject implements IMyObject, and of course, List implements
ICollection.


Because C# generics don't support contravariance/covariance. Even if
they did, you'd need to cast to ICollection<+IMyObject>
(or ICollection<-IMyObject> - I can't remember which way round it is)
rather than ICollection<IMyObject>.

Suppose you *could* cast it. Let's keep things simple and keep it as
casting some IList<string> to IList<object>. It's fine when it comes to
taking elements *out* of the list. It's not so good if you try to add
elements to the list.

Suppose I could do:

IList<string> strings = new List<string>();
IList<object> objects = strings;
// No problem here
object firstObject = objects[0];
// What would this do?
objects.Add (Encoding.UTF8);

It would be trying to add an Encoding to a list of Strings! That would
*have* to fail at runtime, in order to avoid completely violating type
safety. At that stage, you've lost a major point of using generics in
the first place - type safety.

Now, if C# supported covariant/contravariant generics, you *could* do:

IList<string> strings = new List<string>();
IList<+object> objects = strings;

IList<+object> would mean "it's a list of 'something that derives from
object but I don't know what'". (Again, I may have got + and - the
wrong way round, I'm afraid.) That would mean you'd be able to fetch
from the list as object, but not add anything, because you wouldn't
know exactly which type you could add.

Similarly you could do:
IList<object> objects = new List<object>();
IList<-string> strings = objects;

You could then *add* any string to strings, but you couldn't fetch
anything out of it because you wouldn't know what type it was.

I may well have misunderstood all this (in terms of what the CLI
allows) - I've only seen it mentioned in a few places. Anyway, I hope
you can see why C# in its current form, with no added
covariance/contravariance, stops you from doing the cast you want.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Apr 14 '06 #2
Because List<MyObject> is a specific type, and ICollection<MyObject> is a
specific type, and List<MyObject> does not inherit or impment
ICollection<MyObject>. Generics are compiled to strong data types. The
Generic "classes" are not classes at all, but templates used to create
classes at compile time.

--
HTH,

Kevin Spencer
Microsoft MVP
Professional Numbskull

Hard work is a medication for which
there is no placebo.

"Jimp" <Ja***********@hotmail.com> wrote in message
news:11**********************@j33g2000cwa.googlegr oups.com...
Why can't I cast List<MyObject> to ICollection<IMyObject>.

MyObject implements IMyObject, and of course, List implements
ICollection.

Thanks

Apr 14 '06 #3
Kevin Spencer <ke***@DIESPAMMERSDIEtakempis.com> wrote:
Because List<MyObject> is a specific type, and ICollection<MyObject> is a
specific type, and List<MyObject> does not inherit or impment
ICollection<MyObject>.


Yes it does - that would be fine. List<MyObject> doesn't implement
ICollection<IMyObject> though - that's the important bit (the type
parameter).

I'm guessing your post was actually a typo, but I thought it would be
worth clarifying quickly :)

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Apr 14 '06 #4
Why can't I cast List<MyObject> to ICollection<IMyObject>.

MyObject implements IMyObject, and of course, List implements
ICollection.


Just because List<MyObject> implements ICollection<MyObject> doesn't
mean it also implements ICollection<IMyObject>.

Read more at
http://blogs.msdn.com/rmbyers/archiv...16/375079.aspx
Mattias

--
Mattias Sjögren [C# MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Apr 14 '06 #5
Hi Jon,

Yeah, sorry for muddying the water.
--
HTH,

Kevin Spencer
Microsoft MVP
Professional Numbskull

Hard work is a medication for which
there is no placebo.

"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
Kevin Spencer <ke***@DIESPAMMERSDIEtakempis.com> wrote:
Because List<MyObject> is a specific type, and ICollection<MyObject> is a
specific type, and List<MyObject> does not inherit or impment
ICollection<MyObject>.


Yes it does - that would be fine. List<MyObject> doesn't implement
ICollection<IMyObject> though - that's the important bit (the type
parameter).

I'm guessing your post was actually a typo, but I thought it would be
worth clarifying quickly :)

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too

Apr 15 '06 #6

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

Similar topics

0
by: Aaron W. West | last post by:
Fun with CAST! (Optimized SQLServerCentral script posts) I found some interesting "tricks" to convert binary to hexadecimal and back, which allow doing 4 or 8 at a time. Test code first: --...
3
by: Mike | last post by:
I am using MS-Access as a front end for my MS-SQL DB. I have a sql view that uses the following: SELECT TOP 100 PERCENT RECID, PATNUMBER AS , SVCCODE AS , QTY, PROF_CHRGS AS , AMOUNT,...
4
by: Ray | last post by:
When a single-bit bitfield that was formed from an enum is promoted/cast into an integer, does ANSI C say anything about whether that integer should be signed or unsigned? SGI IRIX cc thinks it is...
17
by: Hazz | last post by:
In this sample code of ownerdraw drawmode, why does the '(ComboBox) sender' line of code need to be there in this event handler? Isn't cboFont passed via the managed heap, not the stack, into this...
3
by: mra | last post by:
I want to cast an object that I have created from a typename to the corresponding type. Can anycone tell me how to do this? Example: //Here, Create the object of type "MyClass" object...
5
by: Nick Flandry | last post by:
I'm running into an Invalid Cast Exception on an ASP.NET application that runs fine in my development environment (Win2K server running IIS 5) and a test environment (also Win2K server running IIS...
3
by: John Howard | last post by:
Making the following call to a local MSAccess database works fine: Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs) Dim intRows As Integer Dim strSQL As String Dim ds As New...
9
by: Frederick Gotham | last post by:
Let's assume that we're working on the following system: CHAR_BIT == 8 sizeof( char* ) == 4 (i.e. 32-Bit) Furthermore, lets assume that the memory addresses are distributed as follows: ...
5
by: Frederick Gotham | last post by:
Before I begin, here's a list of assumptions for this particular example: (1) unsigned int has no padding bits, and therefore no invalid bit- patterns or trap representations. (2) All types have...
7
by: * Tong * | last post by:
Hi, I couldn't figure out how to properly type cast in this case: $ cat -n type_cast.c 1 #include <stdio.h> 2 3 typedef unsigned char Byte; 4 typedef signed char Small_Int; 5
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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: 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
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...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
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...

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.