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>
means List<WhateverTypeYouWantItToBeAListOf>
. So for example:
If I have an Employee Class, and I wanted a collection of Employees, I could say:
List<Employee> employeeList = new List<Employee>();
I could then add Employee
Objects to that list, and have it be Type-safe and extend to however many employee objects I put in it.
Like so:
Employee emp1 = new Employee(); Employee emp2 = new Employee(); employeeList.Add(emp1); employeeList.Add(emp2);
employeeList
now holds emp1
and emp2
as 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 Animal
instance inside of List<Employee>
(unless, of course, Employee is a base class that Animal
inherits 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.
You need to substitute T
for another Type such as int
, string
or a class of your creation:
List<int> values = new List<int>();
values.Add(1);
values.Add(2);
int secondNumber = values[1]; // Yay! No casting or boxing required!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With