Got something to write about? Check out our Article Builder.

C# School

By Faraz Rasheed
Last Updated: Monday, November 03, 2008
Covers all you need to know to start programming in .NET and C#, from the basics to advanced topics.
starstarstarstarhalf star
Previous Page        Next Page



Collections
Although we can make collections of related objects using arrays, there are some limitations when using arrays for collections. The size of an array is always fixed and must be defined at the time of instantiation of an array. Secondly, an array can only contain objects of the same data type, which we need to define at the time of its instantiation. Also, an array does not impose any particular mechanism for inserting and retrieving the elements of a collection. For this purpose, the creators of C# and the .Net Framework Class Library (FCL) have provided a number of classes to serve as a collection of different types. These classes are present in the System.Collections namespace. Some of the most common classes from this namespace are:


Class	        Description

ArrayList       Provides a collection similar to an array, but that grows 
                dynamically as the number of elements change.
Stack	        A collection that works on the Last In First Out (LIFO) 
                principle, i.e., the last item inserted is the first item 
                removed from the collection.
Queue	        A collection that works on the First In First Out (FIFO) 
                principle, i.e., the first item inserted is the first item 
                removed from the collection.
Hashtable       Provides a collection of key-value pairs that are organized 
                based on the hash code of the key. 
SortedList      Provides a collection of key-value pairs where the items are 
                sorted according to the key. The items are accessible by both 
                the keys and the index.


All of the above classes implement the ICollection interface, which contains three properties and one method:
  • The Count property returns the number of elements in the collection (similar to the Length property of an Array)
  • The IsSynchronized property returns a boolean value depending on whether access to the collection is thread-safe or not
  • The SyncRoot property returns an object that can be used to synchronize access to the collection.
  • The CopyTo(Array array, int index) method copies the elements of the collection to the array, starting from the specified index.
All the collection classes also implement the IEnumerable interface, so they can be iterated over using the foreach loop.

The ArrayList class
The System.Collections.ArrayList class is similar to arrays, but can store elements of any data type. We don't need to specify the size of the collection when using an ArrayList (as we used to do in the case of simple arrays). The size of the ArrayList grows dynamically as the number of elements it contains changes. An ArrayList uses an array internally and initializes its size with a default value called Capacity. As the number of elements increase or decrease, ArrayList adjusts the capacity of the array accordingly by making a new array and copying the old values into it. The Size of the ArrayList is the total number of elements that are actually present in it while the Capacity is the number of elements the ArrayList can hold without instantiating a new array. An ArrayList can be constructed like this:

	ArrayList list = new ArrayList();


We can also specify the initial Capacity of the ArrayList by passing an integer value to the constructor:

	ArrayList list = new ArrayList(20);


We can also create an ArrayList with some other collection by passing the collection in the constructor:

	ArrayList list = new ArrayList(someCollection);


We add elements to the ArrayList by using its Add() method. The Add() method takes an object of type object as its parameter.

	list.Add(45);
	list.Add(87);
	list.Add(12);


This will add the three numbers to the ArrayList. Now, we can iterate through the items in the ArrayList (list) using a foreach loop:

	static void Main()
	{
		ArrayList list = new ArrayList();
		list.Add(45);
		list.Add(87);
		list.Add(12);
		foreach(int num in list)
		{
			Console.WriteLine(num);
		}
	}


which will print out the elements in the ArrayList as

45
87
12
Press any key to continue


Author's Note: Java developers take note that we did not cast the integers (implicit data type) to its wrapper before passing it to the Add() method, which expects an instance of type object. The reason for this is that in C# boxing is performed automatically and the compiler boxes the value types to the object implicitly.

The ArrayList class has also implemented the indexer property (or index operator) which allow its elements to be accessed using the [] operators, just as you do with a simple array (we will see how to implement indexers in the next lesson). The following code is similar to the above code but uses the indexers to access the elements of the ArrayList.

	static void Main()
	{
		ArrayList list = new ArrayList();
		list.Add(45);
		list.Add(87);
		list.Add(12);
		for(int i=0; i<list.Count; i++)
		{
			Console.WriteLine(list[i]);
		}
	}


The output of the code will be similar to the one presented previously. The above code uses the property Count to find the current number of elements in the ArrayList. Recall that ArrayList inherits this property (Count) from its parent interface ICollection.

A list of some other important properties and methods of the ArrayList class is presented in the following table:


Property or Method	Description

Capacity	        Gets or sets the number of elements the ArrayList
                        can contain.
Count	                Gets the exact number of elements in the ArrayList.
Add(object)	        Adds an element at the end of an ArrayList.
Remove(object)	        Removes an element from the ArrayList.
RemoveAt(int)	        Removes an element at the specified index from the
                        ArrayList.
Insert(int, object)	Inserts an object in the ArrayList at the specified 
                        index.
Clear()	                Removes all the elements from the ArrayList
Contains(object)	Returns a boolean value indicating whether the 
                        ArrayList contains the supplied element or not.
CopyTo()	        Copies the elements of the ArrayList to the array 
                        supplied as a parameter. This method is overloaded 
                        and one can specify the range to be copied and also 
                        from which index of the array copy should start.
IndexOf(object)	        Returns the zero based index of the first occurrence 
                        of the object in the ArrayList. If the object is not 
                        found in the ArrayList, it returns -1.
LastIndexOf(object)	Returns the zero based index of the last occurrence 
                        of the object in the ArrayList.
ToArray()	        Returns an array of type object that contains all 
                        the elements of the ArrayList.
TrimToSize()	        Sets the capacity to the actual number of elements 
                        in the ArrayList.



Previous Page        Next Page


Bookmark: Submit To Digg Submit To reddit Submit To del.icio.us Bookmark With StumbleUpon Bookmark With FaceBook Bookmark With Google Bookmarks
Comments 55 Comments (view all) Post Comment Post a Comment
Joules Castillon says: Student
Edge Posted on Friday, June 13, 2003Edgestarstarstarstarstar
Great master piece... I have never imagined of such programming like Turbo C#... I am expecting that it would be Turbo D... It's an excellent advancement in Computer Science
mkn says: Good Work
Edge Posted on Friday, June 13, 2003Edgestarstarstar
Great stuff for biginners and had a good look of language key elements. Hopefully, the next aritcle will be more interesting.
Asim Ali says: Keep writing !
Edge Posted on Friday, June 13, 2003Edgestarstarstarstarstar
It was really nice to know about the article and it was more nice to read .
says: 5 STAR
Edge Posted on Saturday, June 14, 2003Edgestarstarstarstarstar
Good effort. This will help us to improve our knowledge in the IT field thank u
Edge Posted on Saturday, June 14, 2003Edgestarstarstarstarstar
This text summarizes the .NET architecture, its features like CLR, CLS, CTR. It contains a good comparison between C++, C# and Java. Better than what many books have tried to do.
Edge Posted on Saturday, June 14, 2003Edgestarstarstarstarstar
No doubt the author, Faraz Rasheed , is a master mind. He is one of the best programmers in the university. The way he looks at Object Oriented techniques is really great, out of this world. I was surprised (and was proud too) when I saw him favoring C# in a discussion forum (Vs Java & C++) , which he won too :p Well Best of luck in future Faraz. We all are praying for you.
says: Good work
Edge Posted on Sunday, June 15, 2003Edgestarstarstarstarstar
This course is one of its type and has no parallel. Go ahead , Good Work!!!!!!!! Must continue to work on it with the same zeal:)
Sanjeev Ranjan says: A simple and nice code
Edge Posted on Tuesday, June 17, 2003Edgestarstarstarstarstar
Its a very simple and very easy written code. If any one is new then its good for them also. His explznztion is like a teaching lession in the class. I never seen better then this type of explanations.
Muhammad Adeel says: Great Work
Edge Posted on Tuesday, June 17, 2003Edgestarstarstarstarstar
Its a nice way and very helpful to those who really want to learn.
Syed Tahir Rasul says: wonderfully Awesome
Edge Posted on Wednesday, June 18, 2003Edgestarstarstarstarstar
Well, this is a great article to read at ProgrammersHeavan, one of the great assets on this site. Thank you Fraz
 
Popular resources and forums for programmers on Programmersheaven.com
Assembly, Basic, C, C#, C++, Delphi, Java, JavaScript, Pascal, Perl, PHP, Python, Ruby, Visual Basic
© Copyright 2009 Programmersheaven.com - All rights reserved.
Reproduction in whole or in part, in any form or medium without express written permission is prohibited.
Violators of this policy may be subject to legal action. Please read our Terms Of Use and Privacy Statement for more information.
Publisher: Lars Hagelin. Read the latest words from the publisher here.
Be the first to sign up for Lars Hagelin’s In-depth Outsourcing Newsletter here.
bootstrapLabs Logo A bootstrapLabs project.