Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: System.Object vs Generics

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!

like image 212
Shai UI Avatar asked Dec 12 '10 21:12

Shai UI


1 Answers

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 InvalidCastExceptions 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).

like image 131
illegal-immigrant Avatar answered Sep 19 '22 12:09

illegal-immigrant