[Journal - Why Generics Make Sense In Scripting]

Why Generics Make Sense In Scripting

Friday, June 10, 2005

Generics are about improving compile-time type checking, right? Why do I support them in .NET Console, then?

While there is no compile phase in an interpreter, type checking has to be performed at some point. If you have some data structure like a collection, you have read as well as write access. Type checking occurs on write access only. If the collection is an ArrayList, there is no type checking to speak of; it's very different if the collection is strongly typed. The more strongly typed data you have, the earlier type checking can be performed; and any type mismatch exceptions occurs much closer to the source of the error (ig., assigning an int to a list of strings).

list = new ArrayList()
list.Add(1) // error cause here
Vars.TextSelection = list[0] // type mismatch here 

Another reason is that an interpreter may not support the definition of data types. If you'd like to have data structures more expressive than arrays, generic types such as those introduced here will provide a greater level of expressiveness. The type-safety of generic tuples can be seen as another bonus, but it's quite distinct from the first benefit, expressiveness and rich structuring.

props = new Dictionary<string, string>()
person = new Tuple<string, string, Dictionary<string, string>>("John", "Doe", props)

Update (Saturday, August 6, 2005): Yet another reason is that libraries may expect data of generic type - the interpreter should be able to supply such data.