472,982 Members | 1,366 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,982 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 6920
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,...
2
by: DJRhino | last post by:
Was curious if anyone else was having this same issue or not.... I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 4 Oct 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
0
tracyyun
by: tracyyun | last post by:
Hello everyone, I have a question and would like some advice on network connectivity. I have one computer connected to my router via WiFi, but I have two other computers that I want to be able to...
2
by: giovanniandrean | last post by:
The energy model is structured as follows and uses excel sheets to give input data: 1-Utility.py contains all the functions needed to calculate the variables and other minor things (mentions...
4
NeoPa
by: NeoPa | last post by:
Hello everyone. I find myself stuck trying to find the VBA way to get Access to create a PDF of the currently-selected (and open) object (Form or Report). I know it can be done by selecting :...
3
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be using a very simple database which has Form (clsForm) & Report (clsReport) classes that simply handle making the calling Form invisible until the Form, or all...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 1 Nov 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM) Please note that the UK and Europe revert to winter time on...
3
by: nia12 | last post by:
Hi there, I am very new to Access so apologies if any of this is obvious/not clear. I am creating a data collection tool for health care employees to complete. It consists of a number of...
4
by: GKJR | last post by:
Does anyone have a recommendation to build a standalone application to replace an Access database? I have my bookkeeping software I developed in Access that I would like to make available to other...

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.