Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

generics

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

like image 489
Xaisoft Avatar asked Aug 26 '11 14:08

Xaisoft


2 Answers

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.

like image 52
John Humphreys Avatar answered Sep 18 '22 09:09

John Humphreys


if you have List<T> you are sure that once the object is instantiated the list only contains instances of the T type, in a List<object> you can put anything inside.

Generics are a nice way to write reusable code having strong types at compile time anyway.

like image 30
Davide Piras Avatar answered Sep 18 '22 09:09

Davide Piras