You are on page 1of 2

Lists in C#

http://www.cs.usfca.edu/~wolber/courses/110s/lectures/listInCSharp.htm Interface-- like a class, but just defines the methods that a class must have. Think of it like a specification or a list of requirements. Both Java and C# have an interface representing what all lists should have. In Java, its called List. In C#, IList. ArrayList and LinkedList are classes that implement IList. They both provide the same functionality, but do it differently. When you declare a variable of type IList, it can end up pointing to either an ArrayList or LinkedList, e.g., IList list = new ArrayList(); // equivalent to ArrayList list = new ArrayList(); IList list2 = new LinkedList(); IList list3 = amazon.SearchForMusic("madonna"); // caller doesn't need to know the actual type of list3. Complete C# IList Specification

Key Methods
Add(Object element) -- adds an element to the list. element can be of any type. Equivalent to 'add' in Java. int Count -- this is a data member which is the number of items in list. list[i] -- use an index to get to a particular object.

Iteration
Using methods above... int i=0; while (i<list.Count) { Foo f = (Foo) list[i]; // note that you must cast to whatever the element type is f.doSomething(); }

C# also provides a foreach statement, which makes things easier. foreach (Foo f in list) { f.doSomething(); }

You might also like