Friday, 6 July 2012

Why do we use generics in programming?

Purpose:
  • This question tests whether a developer has experience in writing reusable code. 
  • Many developers see using generics as a badge of honor in how well you can write code.
  • It is a tricky topic since there is so much to it and it differs between how different languages implement them, so often a interviewer might actually have an incorrect view of how it is implementing in .Net itself. So stick to the purpose of Generics because you might get tangled in a very technical discussion about generics if you hit a particular type of interviewer.

Potential Answer:

It allows us to design classes and methods that defer the specifics of the implementation until run-time when it is needed and used by the instantiating client. It prevents boxing and unboxing which is good since there is a performance loss associated with such actions, provides type safety in the form of avoiding runtime exceptions since we use abstractions and generally provides for more modular reusable code.

Generics are implemented in C# in such a way that the genericness is preserved all the way to the bytecode that is generated. This is different to Java that uses the notion of type erasure. Briefly the underlying compiled classes in Java are not actually generic, they compile down to Object and casts, hence it is a compile time artifact and can be subverted at runtime. C# by virtue of the CLR implements generics all the way to byte code allows deep type safety.



No comments:

Post a Comment