2 ms·
Generics are used to defer type setting from compile time to run time, allowing for flexible, yet type-safe constructs. The classic example is a list (in a str
by hugorodgerbrown 13y ago
Generics are used to defer type setting from compile time to run time, allowing for flexible, yet type-safe constructs.
The classic example is a list (in a strongly-typed language) - without generics you would create specialised strongly-typed list classes - you could have a StringList (only strings), an IntList (only ints), etc.
Using generics you can define a single list class of type <T>, where <T> is any type. Then at runtime you would create a List<String> or a List<Int>. Same outcome, less code, easier to maintain.
MSDN has a good intro to C# generics - http://msdn.microsoft.com/en-us/library/ms379564(v=vs.80).aspx http://msdn.microsoft.com/en-us/library/ms379564(v=vs.80).as...
They are less appropriate in dynamic languages, as type-safety isn't a compile time concern.
- throwit1979 13y agoRuntime? Huh? Whether it's static or dynamic is language-dependent. Example: Java in particular does erasure on parameterized types, so generics are only compile-time.
- papsosouid 13y ago>Generics are used to defer type setting from compile time to run time, allowing for flexible, yet type-safe constructs. No. Some languages implement it that way, but nothing about the concept involves moving anything to run time. In languages with reasonable type systems, there is no run time involvement at all.
- zwieback 13y agoHere's another good paper from MS on generics in .NET and C#: http://research.microsoft.com/pubs/64031/designandimplementationofgenerics.pdf http://research.microsoft.com/pubs/64031/designandimplementa... What's interesting is that the .NET CLR directly supports parametric polymorphism. I think the .NET design is nicer than type erasure in Java but Java's approach is more applicable to situations where the runtime can't be modified. No idea how Go fits into that picture.