Alex Rivera | Logout

Difference between List<T> and List<object>?

Asked 2011-08-26T14:27:09.667
11

Since everything inherits from object, what is the difference between List<T> and List<object>? Advantages? Disadvantages?

Edit
Report

2 Answers

3

List takes a generic type as the template argument. So, you will genuinely have a list of cars if you do:

List<car> list = new List<car>();

Whereas:

List<object> objlist = new List<object>();

Can hold references to anything. The problem is, these references are downcasted to objects and you can't use their members and functions until you recast them to the right object. For example, if you held cars in objlist, you'd have to do:

((car)objlist[0]).GetMaker();

To call the cars GetMaker function wehreas with list you could do:

list[0].GetMaker();

This assumes you have at least one car/obj in the list.

answered 2011-08-26T14:31:16.047
1

You can consider T as a type constraint on the List. So if you say

class Vehicle {} 
class Car : Vehicle {}
class Boat : Vehicle {}
class SpeedBoat : Boat {}
List<Boat> listOfBoats 

The list can only contain a type of Boat and it's descendants but not any other Vehicles. If you had set it to object then the List could basically contain any reference type.

Note though that if you want e.g. all SpeedBoats from that collection you can use the nice extension method OfType:

//Returns IEnumerable<SpeedBoat>, casting is done for you
var speedBoats = listOfBoats.OfType<SpeedBoat>(); 
answered 2011-08-26T14:43:15.343

Your Answer