Life Before Generics in C#

Version: C# 1

If we want to print a collections of a string in one method GenerateNames we would do it like this. On the early days of c#.

(This is between 2002 - 2005 before generics we’re introduced.)

The common drawbacks are :

  • It lacked type safety, leading to runtime errors. (This is the most crucial one)

  • It requires manual casting, which was both error- prone.

  • It caused performance issues due to boxing and unboxing of value types.

    Let’s imagine we are c# 1 programmers, and you would typically code GenerateNames method using:
    Arrays

Now the problem is that it’s a fix size because it’s an array right.

Introducing another iteration , now we use ArrayLists.

  • It stores objects, not specific types.

  • It automatically grows in size when you add more items.

ArrayLists

Even tho it solve the problem of fixed array size. The problem is that your compiler trusts you too much. It stores objects.

By adding an integer to our collection , we will have a runtime error. ( this is a crucial one if we want to build robust systems).

Another iteration comes in and then introduce.

String Collections

Now by using StringCollections a specialized collection that only handle strings. It’s much safer because adding non-string values would make the a compilation error. But that doesn’t solve the need for developers of a collection that handles both types.

What if you want to create an int Collection that is type safety? a class collection that is type safety?
inherit on base collection.

Back then a good implementation I would imagine is to create a PersonCollection that wil Inherit on CollectionBase.

Note: also please note that automatic properties that i used is not on c#1 back then. I just used it for smoother demo purposes.

Now you create a personCollection that is safe from runtime errors. I imagine this is what the devs are doing back then.

Now enter the generics.

List<T>

Solves all the problems before :

  • The fixed size of the array

  • The exposed API uses T everywhere it needs to refer to the element type, so you know that a List will contain only string references. You’ll get a compile-time error if you try to add anything else, unlike with ArrayList.

At the time, it was just how things worked. But looking back now, it’s clear how limited and brittle that world really was.

Learning about the pre-generics era gave me a deeper appreciation for what C# offers today. I think knowledge like this is really valuable for us modern developers realize how our language really has evolve. And how thoughtfully C# is crafted.

0
Subscribe to my newsletter

Read articles from Juan Miguel Nieto directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Juan Miguel Nieto
Juan Miguel Nieto

A software developer trying to write organic blogs.