Force Collections to Accept Only One Class in C#

Collections, such as List and ArrayList, in C# used to be able to contain any class. So you could implement the following code without a problem.

ArrayList oldWay = new ArrayList();
oldWay.Add("abc");
oldWay.Add(123);
oldWay.Add(new CustomWhatever());

But sometimes this flexibility caused problems because you might want to limit what could be contained in that list (for example, limit it to string objects). That way when you retrieved an object from that list you wouldn’t have to check that it was the class you wanted it to be.

Starting in .NET Framework 2.0, you could use generics for to limit collections. Here’s an example:

ArrayList<string> newWay = new ArrayList<string>();
newWay.Add("abc");
newWay.Add("def");

You can still do it the old way, but this way has a lot of advantages.

For more details about this, see this post that explains a similar concept in Java.

Leave a Reply