Post Details

Generics And Generic Collections In c Sharp .Net

np

Tue , May 02 2023

np
C# Generic & Non-generic Collections

C# Generic & Non-generic Collections

C# includes specialized classes that store series of values or objects, called collections.

Examples of Collections

int[] array = new int[5];
string[] strArr = new string[1];

The limitation of these collections is that they are strongly typed and have a fixed size.

Types of Collections

There are two types of collections available in C#: non-generic collections and generic collections. Both examples above fall under non-generic collections.

System.Collections namespace contains non-generic collection types, and System.Collections.Generic namespace includes generic collection types.

To overcome type and size limitations, .NET introduced generic collections.

Comparison of Non-generic and Generic Collections

.Net Collection Generic Collection
Array list List (Generic)
Hash table Dictionary
Stack Stack (Generic)
Queue Queue (Generic)

Problem with Array and ArrayList

Array:

  • Arrays are strongly typed, meaning you can only put one type of object into them.
  • Limited size (fixed length).

ArrayList:

  • ArrayLists are strongly typed.
  • Data can grow dynamically as needed.
  • Boxing and unboxing during processing decreases performance.

Example of ArrayList in C#:

var arlist1 = new ArrayList();
arlist1.Add(1);
arlist1.Add("Bill");
arlist1.Add(" ");
arlist1.Add(true);
arlist1.Add(4.5);
arlist1.Add(null);

Example of Generic Type:

class Check {
public bool Compare(UnknowDataType var1, UnknowDataType var2) {
return var1.Equals(var2);
}
}

Generic Collections Description

Generic Collection Description
List Contains elements of the specified type and grows automatically.
Dictionary Contains key-value pairs.
SortedList Stores key-value pairs and automatically sorts them.
Queue Stores values in FIFO (First In First Out) style.
Stack Stores values in LIFO (Last In First Out) style.
HashSet Contains non-duplicate elements.

Examples of All Generic Collections

List listObj = new List();
listObj.Add(123);
listObj.Add(235);
Console.WriteLine("List Second Value: {0}", listObj[1]);
Dictionary objDic = new Dictionary();
objDic.Add(123, "Ramakrishna");
Console.WriteLine("Dictionary Value: {0}", objDic[123]);
You may also like - SSC CPO Notification 2023

Leave a Reply

Please log in to Comment On this post.