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.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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
ArrayListclass, but the downside is that it’s containing type is anobject. So when you’d iterate over the list, you’d have to cast every item to its correct type (eitherstringorAnimal) which is more code and has a performance penalty. Plus, since anArrayListholds objects, it isn’t type-safe. You could still add anAnimalto anArrayListof strings: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:
With a generic
List<string>, this is simply not possible: