Difference between List<T> and List<object>?
Since everything inherits from object, what is the difference between List<T>
开发者_如何学Pythonand List<object>
? Advantages? Disadvantages?
If you insert an int
into List<object>
, it will be boxed. If you insert it into List<int>
, it will not be boxed (this is true for any value type, replacing int
by the name of the type). Similarly for retrieving values from the List<object>
, unboxing will occur, but not for List<int>
.
List<T>
is strongly typed, List<object>
is not (so you lose compile-time safety, and can hit runtime blow ups).
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.
If you use List<object>
you won't have any item typing and will have to cast everything. Plus, that's dangerous because you can put anything into the list and not know exactly what you're getting back for any given item.
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.
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>();
The question is a little confusing but I think jsmarble has hit on one of the main point in that you will have to cast everything to the type you require. The is inefficient, especially with value types which List<T>
will handle without having to box and unbox the value.
You also sacrifice type safety which potentially could result in runtime errors.
精彩评论