Since everything inherits from object, what is the difference between List<T>
and List<object>
? Advantages? Disadvantages?
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.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With