4 ms·
That has very little to do with it. Generics are helpful in cases where you desire type safety but still want to have reusable code. An example that we have r
by seandhi 14y ago
That has very little to do with it. Generics are helpful in cases where you desire type safety but still want to have reusable code. An example that we have run into is in data tables where we want to insert into and retrieve data from the table. Without generics, we have to write a class for every single different type of table because they each represent different data types. To do this generically now, without generics, we would have to sacrifice type safety. With generics, we will be able to write a generic base data table controller, without sacrificing type safety.
It would look something like this:
class DataTable<T> {
Insert(element: T) : void {
//insert code
}
Get(row: number) : T {
//get code
}
//more code
}
Then I could subclass that like:
class ProductDataTable extends DataTable<Product> {
//Done... No need to rewrite everything
}
Or I could just instantiate the base class in an ad hoc fashion:
var productTable = new DataTable<Product>();
In summary, generics will help immensely with common coding tasks.