Working with Collection<T> in C# Language
Objective
In this tutorial we will show you how to use Collection class in C#. Collection class supports some advantages when dealing with group of object, especially when you want to modify and create your own Collection class.
Let's go
In C# language Collection class defines some virtual/abstract members and enables you to override these members to modify their behaviors. You can declare an instance of Collection class and specify the type of elements in this collection, then use some default built-in members of this class, or you can derive from it and create your own Collection class, with index access like an array. Here is the list of some common members of Collection
Name | Description |
Count | Gets the number of elements actually contained in the collection |
Add | Adds an object to the end of the collection |
Clear | Removes all elements from the list |
Contains | Determines whether an element is in the collection |
Bellow is an example of how to use Collections in C#:
- using System;
- using System.Text;
- using System.Collections.ObjectModel;//this namespace must be insert here when you want to use Collection class
- namespace MyFirstProgram
- {
- class CollectionTest
- {
- static void Main(string[] args)
- {
- colObj.TestCollection();
- Console.ReadKey();
- }
- private void TestCollection()
- {
- //declare an collection object which has int type.
- //add elements to collection with Add memeber
- for (int i = 0; i < 10; i++)
- {
- my_collection.Add(i);
- }
- //print number of elements in collection with Count member
- Console.WriteLine("Length of collection " + my_collection.Count);
- }
- }
- }
In above code we declare a collection of type Int and then add elements to our collection, then print the number of elements in this collection. Everything is simple and easy.
Deriving your own collection
In case of making your own collection, you can derive from Collection
Name | Description |
ClearItems | Removes all elements from the collection. Can change the behavior of the Clear method. |
InsertItem | Inserts an element into the collection at the specified index. |
RemoveItem | Removes the element at the specified index |
SetItem | Replaces the element at the specified index. |
Example bellow demonstrate how you can derive and make your own class:
- public class IntCollection : Collection<int>
- {
- protected override void InsertItem(int index, int item)
- {
- Console.WriteLine("Insert new item {0} at position {1}", item, index);
- Base.InsertItem(index, item);
- }
- static void Main(string[] args)
- {
- colObj.InsertItem(0, 1);
- Console.WriteLine("Length of collection " + colObj.Count);
- Console.ReadKey();
- }
- }
Here we declare an IntCollection class that derives from Collection
Summary
This tutorial has introduced you how to use Collection
Comments
Add new comment
- Add new comment
- 127 views