I’m trying to build my first generic list and have run into some problems. I understand the declaration looks like ‘ List<T> ‘, and I have using System.Collections.Generic; at the top of my page. However, Visual Studio doesn’t recognize the T variable.
What am I missing?
List<T>meansList<WhateverTypeYouWantItToBeAListOf>. So for example:If I have an Employee Class, and I wanted a collection of Employees, I could say:
I could then add
EmployeeObjects to that list, and have it be Type-safe and extend to however many employee objects I put in it.Like so:
employeeListnow holdsemp1andemp2as objects.There are several facets to generic collections, the most important being they provide an object independent way of having a… well… collection of objects. They are type-safe; which means that any collection will consist of one type of object. You won’t have a
Animalinstance inside ofList<Employee>(unless, of course, Employee is a base class thatAnimalinherits from. At that point, however, you have bigger problems.Programming with Generics is its own topic, worthy of (at least) one chapter in a book. At a very high level, programming with generics provides another way to reuse code — independent of any class hierarchy or implementation details of a specific class.
More information here.