why Generics ?

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.
 
J

Jon Skeet [C# MVP]

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[].
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top