Basics of .NET Collections in C#


In project some time we need create and manage group of related objects, For that C# have some special things is know as collection.In collection we have Generic also its intro in C#2.0 This Article may useful for know the Collection in C#.

A collection is a set of similarly typed objects that are grouped together.


1. ArrayList : Array of objects whose size is dynamically increased as required.


ArrayList obj = new ArrayList();

List.Add(1);
List.Add(2);
ForEach(object O in obj)
{
Console.WriteLine(O.tostring());
}


2. HashTable : Its have unique value store in the key and value.

Hashtable hash = new hashtable();

Hash.Add( 1,"rathi")


3. List : Its dynamically Allocation of Array

List lt = new List();

In List We can use Tuple also for multiple parameters.


4. Dictionary : used with type parameters to store keys and values of specific types

Dictionary dict = new Dictionary();


Difference between Dictionary and Hashtable

Dictionary:
•It returns error if we try to find a key which does not exist.
•It is faster than a Hash Table because there is no boxing and unboxing.
•Only public static members are thread safe.
•Dictionary is a generic type which means we can use it with any data type.

Hashtable:
•It returns null if we try to find a key which does not exist.
•It is slower than dictionary because it requires boxing and unboxing.
•All the members in a Hashtable are thread safe,
•Hashtable is not a generic type,


Array: collection of datatype

Int [] num = new int[5]


5. Queue
A First in,First out of object

static void Main()
{
Queue collectionQueue = new Queue();
collectionQueue.Enqueue(5);
collectionQueue.Enqueue(6);
foreach (int value in collectionQueue)
{
Console.WriteLine(value);
}
}

6. Stack
A last in,First out in object

Static Stack GetStackList()
{
Stack stack = new Stack();
stack.Push(1);
stack.Push(2);
stack.Push(3);
return stack;
}
static void Main()
{
Var Varstack = GetStackList ();
foreach (int i in Varstack)
{
Console.WriteLine(i +"Stack values");
}
}


Comments

Author: Ritesh07 May 2014 Member Level: Bronze   Points : 0

Short and Good information.



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: