In the recent posts, I’ve constantly referred to generics. The concept of generics is to simply provide classes (collections) with placeholders for types, and let them work with the given types. In this manner, type-safety can be enforced, and performance will be increased by evading the constant converts from a type to another.
Let’s consider the following example: we have a List collection, and we’d like to assign strings for it. But nothing prevents us from assigning for example an Exception, as a mistake. Even worse, we can create a useless pile of junk from our List collection (there is no reason why we should, the key point here is that we can). Now, by using the List<string> generic class, we can rest assured that our collection can only contain strings. It is beautiful, and even better, it works with everything, even your custom classes.
This objective means that you can use the classes that can be found in the System.Collections.Specialized namespace. Unfortunately, there are a bunch of classes that you’ll never use in a live environment (remember the magic keyword: Generics), but you’ll have to know them for the exam.
We’ll deal with the following classes in this post:
Before taking any step forward, please note that the collection classes presented here are obsolete. This is because they have generic counterparts, with which we’ll deal later. For the exam, you should know these classes, but in the real life, use generics instead.
First let’s see the interfaces which will be useful when defining our custom collection classes: IEnumerator and IEnumerable. These interfaces are the only way to iterate over your data in a foreach loop. You decorate your class (or struct) with the IEnumerable interface, which has a method named GetEnumerator, of type IEnumerator. Note that you can use a foreach loop without implementing IEnumerable. Simply create a method in your class with the name of GetEnumerator, and the type of IEnumerator. Then you can make use of the yield keyword, which returns data, and stores the position of the index. Syntax: