473,397 Members | 2,028 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,397 software developers and data experts.

difference between List<object> and List<MyClass>

Hi

I seem to have a bit of trouble understanding one bit of how generics work:

In C#, every class automatically derives from object, and inherits a bunch
of properties (i.e. ToString()). Thus,

(MyClass is object) should always evaluate as true.

However, if I have a method with the following signature:

private void myMethod(List<objectinput)

And I try to call it

myMethod(new List<MyClass>())

the compiler complains that it cannot convert from
System.Collections.Generic.List<MyNamespace.MyClas sto
System.Collections.Generic.List<object>. And if I try to cast List<MyClass>
to List<objectthat doesn't work either.

Likewise

List<objectmyObjs = new List<object>();
myObjs.AddRange(new List<MyClass>());

fails with the same error. However, if I I fill up myObjs as follows:

List<objectmyObjs = new List<object>();
List<MyClassmyClasses = new List<MyClass>();
foreach (MyClass c in myClasses)
{
myObjs.Add((object)c);
}

then it works. Even if I leave away the cast to object in the line
myObjs.Add(..) it works (as is to be expected since MyClass is an object.

Since ever class derives from object, why do the the first two examples not
work? Does class inheritance not translate into generics inheritance?

Regards
Stephan
Jul 25 '07 #1
9 6960
just because MyClass : object, it does not follow that List<MyClass:
List<object>

What you need is:

private void myMethod<T>(List<Tinput) {}

you can now use
List<MyClassdata = blah;
myMethod(data); // note the compiler infers T

Marc

Jul 25 '07 #2
On Jul 25, 11:08 am, "Stephan Steiner" <stephan.stei...@nextiraone.ch>
wrote:

<snip>
Since ever class derives from object, why do the the first two examples not
work? Does class inheritance not translate into generics inheritance?
It doesn't translate into type parameter inheritance. Or rather,
generic types aren't covariant in their type parameters, to use the
jargon :)

In short, a List<stringisn't a List<object>. This actually adds to
type safety - because one of the things you can do with a List<object>
is add *any* object to it, whereas you can't do that with a
List<string(you can only add strings).

Suppose the following were valid:
List<stringstrings = new List<string>();
List<objectobjects = strings;
objects.Add(new object());

The first and third lines are definitely valid - so the only chance
for catching the problem at compile time is for the second line to be
invalid.

Suppose it's valid though - what would you expect to happen? Either it
should blow up at runtime, or the list of strings contains a non-
string. One of the ideas of generics is to push type safety to
compilation time rather than runtime - hence the error.

Jon

Jul 25 '07 #3
One of the ideas of generics is to push type safety to
compilation time rather than runtime - hence the error.
Just to tie the two posts together, Jon's explanation neatly
covers *why* the "myMethod<T>(List<Tinput)" trick works -
inside myMethod, you can now (as an example) add any item
to "input", *as long as* it is castable to T. So:

input.Add(new object());

would fail at compile time, but:

input.Add(new T());

would be fine, given a suitable constructor condition on T:

void myMethod<T>(List<Tinput) where T : new() {}

If you want to allow lists of some class / interface (e.g. to
use properties / methods of such), then the "obvious" (but
wrong) waty to do this is:

myMethod(List<ISomeInterfaceinput) {} // not ideal; very restrictire

this is better expressed via a condition:

void myMethod<T>(List<Tinput) where T : ISomeInterface {}

or if you want to allow arrays, collections, etc to be passed in:

void myMethod<T>(IList<Tinput) where T : ISomeInterface {}

Marc

Jul 25 '07 #4
In article <11**********************@22g2000hsm.googlegroups. com>,
ma**********@gmail.com says...
void myMethod<T>(List<Tinput) where T : ISomeInterface {}

or if you want to allow arrays, collections, etc to be passed in:

void myMethod<T>(IList<Tinput) where T : ISomeInterface {}
Did you mean IEnumerable<Tinstead of IList<T>? You cannot pass an
array when input parameter is declared as IList<T>. You can pass both
arrays and lists if input was defined as IEnumerable<T>.

--
Marcin Hoppe (marcin.hoppe at gmail.com)
Jul 25 '07 #5
Did you mean IEnumerable<Tinstead of IList<T>?

I meant IList<T>
You cannot pass an array when input parameter is declared as IList<T>.
Yes you can (working example below). Add() etc will obviously throw an
exception (presumably NotSupported... or InvalidOperation...), but
many of the IList<Tfunctions will work fine, such as enumeration,
length query and indexer access - all perfectly type safe.

Marc

using System;
using System.Collections.Generic;
using System.Diagnostics;

static class Program {
static void Main() {
int[] data = { 1, 3, 5 };
Test(data);
}
static void Test<T>(IList<Tlist) {
foreach (T item in list) {
Debug.WriteLine(item);
}
}
}

Jul 25 '07 #6
Not sure if my last post went out, but yes I meant IList<T>, and yes
it works just fine. Add() isn't supported, but you can check the
length, enumerate, use the indexer, etc.

Marc

Jul 25 '07 #7
In article <11**********************@19g2000hsx.googlegroups. com>,
ma**********@gmail.com says...
Not sure if my last post went out, but yes I meant IList<T>, and yes
it works just fine. Add() isn't supported, but you can check the
length, enumerate, use the indexer, etc.
I wasn't aware of that. MSDN says that both in C# 1.2 and 2.0 a single
dimensional array implements IList (or IList<T>).

Interesting thing is the way method IList.Clear works. It sets all the
elements of the array either to 0, false or null, whichever is
appropriate. The IList<T>.Clear, however, throws an exception.

Thanks for a good point!

--
Marcin Hoppe (marcin.hoppe at gmail.com)
Jul 26 '07 #8
Interesting thing is the way method IList.Clear works. It sets all the
elements of the array either to 0, false or null, whichever is
appropriate. The IList<T>.Clear, however, throws an exception.
Interesting; I didn't know that...

Personally, I think the exception (IList<T>) is the correct
implementation; if
all you have is a list, you expect Clear() to remove the elements.
Since you
can't remove from an array, it makes sense to throw. I guess the IList
approach was somebody trying to be clever, and ignoring the meaning
from
the contract:

IList.Clear Method ... Removes all items from the IList.
(http://msdn2.microsoft.com/en-us/library/
system.collections.ilist.clear.aspx)

Marc

Jul 26 '07 #9
In article <11**********************@22g2000hsm.googlegroups. com>,
ma**********@gmail.com says...
Interesting; I didn't know that...

Personally, I think the exception (IList<T>) is the correct
implementation; if
all you have is a list, you expect Clear() to remove the elements.
Since you
can't remove from an array, it makes sense to throw. I guess the IList
approach was somebody trying to be clever, and ignoring the meaning
from
the contract:

IList.Clear Method ... Removes all items from the IList.
(http://msdn2.microsoft.com/en-us/library/
system.collections.ilist.clear.aspx)
Yup. I also think than an exception would be the preferred way to go.

--
Marcin Hoppe (marcin.hoppe at gmail.com)
Jul 26 '07 #10

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

Similar topics

1
by: GRiN | last post by:
In VS2003 I have been using an ArrayList loading it with a copy constructor and it seems to work fine. {I am acutally loading a lot of constants first, not one a shown} public ArrayList al;...
5
by: Gary | last post by:
I am using List<MyClassto store a bunch of MyClasses. And in my program, I want to change the content of one class in this list. However, it seems to me that this list keeps an original copy and is...
0
by: adebaene | last post by:
Hello all, Has everyone tried to use the functions taking a Predicate in Generics container in C++/CLI? Say I have a List<MyClass^>^ my_array, and I want to call RemoveAll on it. How would...
2
by: Jamie Risk | last post by:
As an example supposing I have an object: public class myClass { public List<bytelistOfBytes; public int X; public int Y; } and a method ("op()") whose signature is:
5
by: Stephan Steiner | last post by:
Hi I seem to have a bit of trouble understanding one bit of how generics work: In C#, every class automatically derives from object, and inherits a bunch of properties (i.e. ToString()). Thus,...
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
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
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.