I'm having a hard time understanding when to use Object (boxing/unboxing) vs when to use generics.
For example:
public class Stack { int position; object[] data = new object[10]; public void Push (object o) { data[position++] = o; } public object Pop() { return data[--position]; } }
VS.
public class Stack<T> { int position; T[] data = new T[100]; public void Push(T obj) {data[position++] = obj; } public T Pop() { return data[--position]; } }
Which one should I use and under what conditions? It seems like with the System.Object way I can have objects of all sorts of types currently living within my Stack. So wouldn't this be always preferable? Thanks!
Always use generics! Using object's results in cast operations and boxing/unboxing of value-types. Because of these reasons generics are faster and more elegant (no casting). And - the main reason - you won't get InvalidCastException
s using generics.
So, generics are faster and errors are visible at compile-time. System.Object
means runtime exceptions and casting which in general results in lower performance (sometimes MUCH lower).
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