why Generics ?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi,

I've heard about generics in C#(Whidbey) which is much like templates in
C++. As per my understanding, since C++ doesn't have universal base class
concept so templates are important. Why templates are important in C# when
everything in C# ultimately derives from class "object".

For example, I can build a collection class for type "object" and it will
work for all the primitive as well as non primitive types since all types are
derived from class "object". Even one can build strongly typed collections
using "object" paradigm.

Question: If it can be done this way, then why generics ?? What benefits
Generics offers ??

Regards,
Hatim Ali.
 
Hatim Ali said:
I've heard about generics in C#(Whidbey) which is much like templates in
C++. As per my understanding, since C++ doesn't have universal base class
concept so templates are important. Why templates are important in C# when
everything in C# ultimately derives from class "object".

For type safety and performance.
For example, I can build a collection class for type "object" and it will
work for all the primitive as well as non primitive types since all types are
derived from class "object". Even one can build strongly typed collections
using "object" paradigm.

Question: If it can be done this way, then why generics ?? What benefits
Generics offers ??

Compile-time type safety without building a different strongly typed
collection class for each type. Instead of having to have a
StringCollection, FooCollection, BarCollection etc, we can just use
List<String>, List<Foo>, List<Bar> etc.

It also enables collections of value types without boxing. List<byte>
for instance is in some ways similar to a MemoryStream - it's got an
internal array of type byte[] rather than (with ArrayList) object[].
 
Back
Top