Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are Generic Collections in C#? [duplicate]

Tags:

c#

.net

generics

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?

like image 535
Agile Noob Avatar asked Dec 11 '08 23:12

Agile Noob


2 Answers

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.

like image 174
George Stocker Avatar answered Oct 10 '22 05:10

George Stocker


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!
like image 30
Andrew Kennan Avatar answered Oct 10 '22 06:10

Andrew Kennan