←to practical programming

Note "generics in C-sharp"

Generics (parametrized types) in C-sharp are like templates in C++ only with somewhat limited capabilities (but, allegedly, increased safety). In particular, it is not possible to call arithmetic operators on generic types, which makes C-sharp generics less useful for scientific computing (correction: it seems that version 7 actually allows to do this via interfaces, but we don't do interfaces in this course).

One can declare a generic class (or a generic method) using---just like in C++ and Java---angle brackets. For example, here is a (primitive) class implementing a generic list container where you can add items of a given type,

public class genlist<T>{               /* "T" is the type parameter */
   private T[] data;                   /* we keep items in the array "data" */
   public int size => data.Length;     /* I think that "size" sounds better than "Length" */
   public T this[int i] => data[i];     /* we get items from our list using [i] notation */
   public genlist(){ data = new T[0]; }  /* constructor creates empty list */
   public void add(T item){              /* add item of the type "T" to the list */
      T[] newdata = new T[size+1];   /* we need a larger array (inefective but uses minimal memory) */
      Array.Copy(data,newdata,size); /* here you do O(size) operations */
      newdata[size]=item;            /* add the item at the end of the list */
      data=newdata;                  /* old data should be garbage collected, no worry here */
      }
}
The container can be used as
genlist<int> list = new genlist<int>();
list.add(1);
list.add(2);
list.add(3);
for(int i=0;i<list.size;i++)WriteLine(list[i]);
Actually, there is a built-in System.Collection.Generic.List container [].