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

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

+6
source share
6 answers

If you type int in a List<object> , it will be inserted into the box. If you paste it into a List<int> , it will not be boxed (this is true for any type of value, replacing int with the type name). Similarly, to retrieve values ​​from a List<object> an unlock will occur, but not for a List<int> .

List<T> strongly typed, List<object> not (therefore you lose security during compilation and can hit explosions in run mode).

+11
source

if you have a List<T> , you are sure that as soon as the object is created, the list contains only instances of type T, in the List<object> you can put something inside.

Generics are a good way to write reusable code with strong types at compile time.

+9
source

If you use List<object> , you will not have text input and you will need to drop everything. In addition, it is dangerous because you can put something on the list and not know exactly what you get for any given item.

+4
source

The list takes a generic type as an argument to the template. So, you really will have a list of cars if you do this:

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

While:

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

May contain links to anything. The problem is that these links are omitted to objects, and you cannot use their members and functions until you remake them to the desired object. For example, if you keep cars in objlist, you would need:

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

To call the GetMaker function for cars, a list you could make:

 list[0].GetMaker(); 

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

+2
source

You can think of T as a type restriction in a list. Therefore, if you say

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

The list may contain only the type of boat and its descendants, but not any other Vehicles. If you set it for an object, then List could basically contain any reference type.

Please note that if you want, for example, all SpeedBoats from this collection, you can use the beautiful OfType extension method:

 //Returns IEnumerable<SpeedBoat>, casting is done for you var speedBoats = listOfBoats.OfType<SpeedBoat>(); 
+1
source

The question is a bit confusing, but I think jsmarble has touched on one of the main points that you will need to throw everything at the type you need. This is inefficient, especially with the types of values ​​that List<T> will process without having to insert and release the value.

You also sacrifice type security that could potentially lead to runtime errors.

0
source

Source: https://habr.com/ru/post/895978/


All Articles