I looked at some sample code using C# generics. Why and when should I use them?
All the examples were complex. I need a simple, clear example that gets me started with C# generics.
A very simple example is the generic List<T>
class. It can hold a number of objects of any type. For example, you can declare a list of strings (new List<string>()
) or a list of Animals (new List<Animal>()
), because it is generic.
What if you couldn't use generics? You could use the ArrayList
class, but the downside is that it's containing type is an object
. So when you'd iterate over the list, you'd have to cast every item to its correct type (either string
or Animal
) which is more code and has a performance penalty. Plus, since an ArrayList
holds objects, it isn't type-safe. You could still add an Animal
to an ArrayList
of strings:
ArrayList arrayList = new ArrayList();
arrayList.Add(new Animal());
arrayList.Add("");
So when iterating an ArrayList you'd have to check the type to make sure the instance is of a specific type, which results in poor code:
foreach (object o in arrayList)
{
if(o is Animal)
((Animal)o).Speak();
}
With a generic List<string>
, this is simply not possible:
List<string> stringList = new List<String>();
stringList.Add("Hello");
stringList.Add("Second String");
stringList.Add(new Animal()); // error! Animal cannot be cast to a string