Mastering C#: Unraveling the Concepts of C# & OOPS
C# Important Concepts- (Generics & Collection)
What is Generics in C#? It allow us to define the specification of the data type of programming elements in a class or a method, until it is actually used in the program. In other words, generics allow us to write a class or method that can work with any data type. We write the specifications for the class or the method, with substitute parameters for data types. When the compiler encounters a constructor for the class or a function call for the method, it generates code to handle the specific data type.
Generics are most frequently used with Collections and the methods that operate on them. It also helps to avoid unpleasant problems like type casting and boxing.
A generic type is declared by specifying a type parameter in angle brackets after a type name where Typename<T> where T is a type parameter. It isn’t mandatory to put the “T” word in the Generic type definition. You can use any word in the TestClass<> class declaration.
What is Collections in C#? Collections standardize the way of which the objects are handled by your program. In other words, it contains a set of classes to contain elements in a generalized manner. With the help of collections, the user can perform several operations on objects like the store, update, delete, retrieve, search, sort etc. C# divide collection in several classes, some of the common classes are shown below:
Generic Collections
C# includes the following generic collection classes in the System.Collections.Generic
namespace.
Generic Collections | Description |
List<T> | Generic List<T> contains elements of specified type. It grows automatically as you add elements in it. |
Dictionary<TKey,TValue> | Dictionary<TKey,TValue> contains key-value pairs. |
SortedList<TKey,TValue> | SortedList stores key and value pairs. It automatically adds the elements in ascending order of key by default. |
Queue<T> | Queue<T> stores the values in FIFO style (First In First Out). It keeps the order in which the values were added. It provides an Enqueue() method to add values and a Dequeue() method to retrieve values from the collection. |
Stack<T> | Stack<T> stores the values as LIFO (Last In First Out). It provides a Push() method to add a value and Pop() & Peek() methods to retrieve values. |
Hashset<T> | Hashset<T> contains non-duplicate elements. It eliminates duplicate elements. |
Non-generic Collections
Non-generic Collections | Usage |
ArrayList | ArrayList stores objects of any type like an array. However, there is no need to specify the size of the ArrayList like with an array as it grows automatically. |
SortedList | SortedList stores key and value pairs. It automatically arranges elements in ascending order of key by default. C# includes both, generic and non-generic SortedList collection. |
Stack | Stack stores the values in LIFO style (Last In First Out). It provides a Push() method to add a value and Pop() & Peek() methods to retrieve values. C# includes both, generic and non-generic Stack. |
Queue | Queue stores the values in FIFO style (First In First Out). It keeps the order in which the values were added. It provides an Enqueue() method to add values and a Dequeue() method to retrieve values from the collection. C# includes generic and non-generic Queue. |
Hashtable | Hashtable stores key and value pairs. It retrieves the values by comparing the hash value of the keys. |
BitArray | BitArray manages a compact array of bit values, which are represented as Booleans, where true indicates that the bit is on (1) and false indicates the bit is off (0). |
Example of List<T>
// C# program to illustrate the concept
// of generic collection using List<T>
using System;
using System.Collections.Generic;
class Geeks {
// Main Method
public static void Main(String[] args)
{
// Creating a List of integers
List<int> mylist = new List<int>();
// adding items in mylist
for (int j = 5; j < 10; j++) {
mylist.Add(j * 3);
}
// Displaying items of mylist
// by using foreach loop
foreach(int items in mylist)
{
Console.WriteLine(items);
}
}
}
Output:
15
18
21
24
27
Advantages of Arrays:
Arrays store multiple data of similar types with the same name.
It allows random access to elements.
As the array is of fixed size and stored in contiguous memory locations there is no memory shortage or overflow.
It is helpful to store any type of data with a fixed size.
Since the elements in the array are stored at contiguous memory locations it is easy to iterate in this data structure and unit time is required to access an element if the index is known.
Disadvantages of Arrays:
The array is static in nature. Once the size of the array is declared then we can’t modify it.
Insertion and deletion operations are difficult in an array as elements are stored in contiguous memory locations and the shifting operations are costly.
The number of elements that have to be stored in an array should be known in advance.
Wastage of memory is the main problem in the array. If the array size is big the less allocation of memory leads to wastage of memory.
ArrayList
The ArrayList
is a non-generic collection of objects whose size increases dynamically. It is the same as Array except that its size increases dynamically.
An ArrayList
can be used to add unknown data where you don't know the types and the size of the data. It included in the System.Collections
namespace
using System.Collections;
ArrayList arlist = new ArrayList();
// or
var arlist = new ArrayList(); // recommended
Example 1: Adding Elements in ArrayList
// Adding elements using ArrayList.Add() method
var arlist1 = new ArrayList();
arlist1.Add(1);
arlist1.Add("Bill");
arlist1.Add(" ");
arlist1.Add(true);
arlist1.Add(4.5);
arlist1.Add(null);
// adding elements using object initializer syntax
var arlist2 = new ArrayList()
{
2, "Steve", " ", true, 4.5, null
};
Example 2: Adding Entire Array/ArrayList into ArrayList
var arlist1 = new ArrayList();
var arlist2 = new ArrayList()
{
1, "Bill", " ", true, 4.5, null
};
int[] arr = { 100, 200, 300, 400 };
Queue myQ = new Queue();
myQ.Enqueue("Hello");
myQ.Enqueue("World!");
arlist1.AddRange(arlist2); //adding arraylist in arraylist
arlist1.AddRange(arr); //adding array in arraylist
arlist1.AddRange(myQ); //adding Queue in arraylist
ArrayList Methods
Methods | Description |
Add()/AddRange() | Add() method adds single elements at the end of ArrayList. |
AddRange() method adds all the elements from the specified collection into ArrayList. |
| Insert()/InsertRange() | Insert() method insert a single elements at the specified index in ArrayList.
InsertRange() method insert all the elements of the specified collection starting from specified index in ArrayList. |
| Remove()/RemoveRange() | Remove() method removes the specified element from the ArrayList.
RemoveRange() method removes a range of elements from the ArrayList. |
| RemoveAt() | Removes the element at the specified index from the ArrayList. |
| Sort() | Sorts entire elements of the ArrayList. |
| Reverse() | Reverses the order of the elements in the entire ArrayList. |
| Contains | Checks whether specified element exists in the ArrayList or not. Returns true if exists otherwise false. |
| Clear | Removes all the elements in ArrayList. |
| CopyTo | Copies all the elements or range of elements to compitible Array. |
| GetRange | Returns specified number of elements from specified index from ArrayList. |
| IndexOf | Search specified element and returns zero based index if found. Returns -1 if element not found. |
| ToArray | Returns compitible array from an ArrayList. |
Thanks for your time. I hope this post was helpful and gave you a mental model for Collections in C#! Will continue in detail for each objects i next blogs.