Non-Generic Collections
Non-Generic collections in C# are a part of the System.Collections namespace. These collections can hold any types of data because they store the data as an object. This means you can store different types of data in a single collection. However, this feature also comes with its own disadvantages. This tutorial will help you understand the basics of Non-Generic Collections in C#.
What is Non-Generic Collection?
Non-Generic Collections are dynamic arrays and do not have a fixed size. They can increase and decrease their size dynamically. These collections are not type-safe which means they can store any type of data in it.
The four types of non-generic collections are:
- ArrayList
- Hashtable
- Stack
- Queue
ArrayList
The ArrayList is a Non-Generic type of collection in C#. This means it can store any type of data in it.
Creating an ArrayList:
ArrayList arrayList = new ArrayList();
Adding elements to ArrayList:
arrayList.Add(1);
arrayList.Add("Two");
arrayList.Add(3.0);
Hashtable
A Hashtable stores key-value pairs. It contains values based on the key.
Creating a Hashtable:
Hashtable hashtable = new Hashtable();
Adding elements to Hashtable:
hashtable.Add(1, "One");
hashtable.Add(2, "Two");
hashtable.Add(3, "Three");
Stack
A Stack is a special kind of collection that follows the LIFO (Last In First Out) principle. This means that the last element added to the stack will be the first one to be removed.
Creating a Stack:
Stack stack = new Stack();
Adding elements to Stack:
stack.Push(1);
stack.Push(2);
stack.Push(3);
Queue
A Queue is another special kind of collection that follows the FIFO (First In First Out) principle. This means that the first element added to the queue will be the first one to be removed.
Creating a Queue:
Queue queue = new Queue();
Adding elements to Queue:
queue.Enqueue(1);
queue.Enqueue(2);
queue.Enqueue(3);
Disadvantages of Non-Generic Collections
Not Type Safe: Non-generic collections are not type safe. They can store any type of data in them. This can lead to errors if you try to perform an operation on the wrong type of data.
Performance: Non-generic collections store data as an object. So, when you store or retrieve data from a non-generic collection, boxing and unboxing occur. These processes consume unnecessary CPU cycles and can degrade performance.
Conclusion
Non-Generic collections in C# can store any type of data, and they are dynamic, meaning their size can increase or decrease at runtime. We have four types of Non-Generic collections in C#: ArrayList, Hashtable, Stack, and Queue. However, due to their non type-safe nature and performance issues related to boxing and unboxing, generic collections are often a better choice.