0% found this document useful (0 votes)
4 views

4 OOP Generics Collections

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

4 OOP Generics Collections

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Object Oriented Programming (OOP)

4. Generics and Collections in C#

Dr. Rida El Chall

Lebanese University – Faculty of Engineering

3rd year – Semester 5


2024 - 2025
1
Outline

▪ What are Generics?


▪ Why use Generics in C#?
▪ What are Collections?
▪ Types of Collections

▪ Generics and collections are fundamental concepts that are used to create reusable
and type-safe code for handling groups of objects.

3rd year - Electrical Engineering Generics and Collections in C# 2


Generics in C#

▪ Generics define classes, interfaces, and methods with placeholders for the data
types they operate on. <T> { }
▪ Use generic types to maximize code reuse, type safety, and performance.
▪ Generics are most frequently used with collections and the methods that operate
on them.
▪ Syntax: public class/interface className<T> { }
▪ Generic Methods: public void methodName<T> (T input) { … }

3rd year - Electrical Engineering Generics and Collections in C# 3


Generics in C# Example

3rd year - Electrical Engineering Generics and Collections in C# 4


Collections in C#

▪ Collections in C# are data structures used to store and manipulate groups of objects.
▪ These collections are provided by the .NET Framework and offer various
functionalities like adding, removing, and iterating over elements.
▪ Two Types of Collections:
▪ Non-generic collections (ArrayList, Hashtable, … )
▪ Generic collections
▪ List<T>, Dictionary<TKey, TValue>, Queue<T>, Stack<T> …
▪ using System.Collections, System.Collections.Generic
▪ Non-generic collections like ArrayList and Hashtable store elements as objects, which
can lead to runtime type errors. To avoid these issues, it is generally recommended to
use generic collections over non-generic ones.

3rd year - Electrical Engineering Generics and Collections in C# 5


Non-generic Collections (Not recommended)
Non-generic
Usage
Collections
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.
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 provides an Enqueue()
method to add values and a Dequeue() method to retrieve values
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).
3rd year - Electrical Engineering Generics and Collections in C# 6
Collections in C#
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 provides an Enqueue() method to add values and a Dequeue()
method to retrieve values.
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.

3rd year - Electrical Engineering Generics and Collections in C# 7


generic versus non-generic collections

▪ A generic collection in C# is strongly typed. That means the data type of the
elements is known at compile time.
▪ This is in contrast to non-generic collections which can store any type of object,
and type information is not known until runtime.

3rd year - Electrical Engineering Generics and Collections in C# 8


ArrayList Example

▪ Use the Add() method to add elements in an ArrayList.


▪ Use the AddRange(ICollection c) method to add an entire Array, HashTable,
SortedList, ArrayList, BitArray, Queue, and Stack in the ArrayList.

3rd year - Electrical Engineering Generics and Collections in C# 9


List<T>
▪ List<T>: List is a dynamic array that can grow or shrink in size. It provides methods for
adding, removing, and accessing elements.
List<int> numbers = new List<int>();
numbers.Add(1);
var names = new List<string> { "<name>", "Ana", "Felipe" };
names.Add("Maria");
names.Remove("Ana");
▪ refer individual items by index names[i]
▪ Count property: return the number of elements in the list , e.g. names.Count
▪ Contains methods checks if the list contains an element, e.g. names.Contains("Bob");
▪ IndexOf method searches for an item and returns the index of the item. If the item isn't
in the list, IndexOf returns -1.
▪ var index = names.IndexOf("Felipe");
▪ Sort method sorts all the items in the list
▪ names.Sort();

3rd year - Electrical Engineering Generics and Collections in C# 10


Dictionary<TKey, TValue>

▪ Dictionary is a collection of key-value pairs where each key is unique. It provides


fast lookup by key.
using System.Collections.Generic;
Dictionary<string, int> ages = new Dictionary<string, int>();
ages["Alice"] = 30;
ages["Bob"] = 35;
ages["Charlie"] = 40;
// Commonly used methods and properties:
// Returns the number of key-value pairs in the dictionary.
ages.Count;
// Returns true if the dictionary contains the key "Bob", otherwise false.
ages.ContainsKey("Bob");
// Removes the entry with the key "Alice" from the dictionary.
ages.Remove("Alice");
3rd year - Electrical Engineering Generics and Collections in C# 11
Queue<T>

▪ Queue is a collection that follows the FIFO (First-In-First-Out) principle. Elements


are added to the end of the queue and removed from the beginning.
using System.Collections.Generic;

Queue<string> queue = new Queue<string>();


queue.Enqueue("First");
queue.Enqueue("Second");
queue.Enqueue("Third");
// Returns the number of elements in the queue.
queue.Count;
// Returns the object at the beginning of the queue without removing it
queue.Peek();
// Removes and returns the object at the beginning of the queue.
queue.Dequeue();
3rd year - Electrical Engineering Generics and Collections in C# 12
Stack<T>

▪ Stack is a collection that follows the LIFO (Last-In-First-Out) principle. Elements


are added to and removed from the top of the stack.
using System.Collections.Generic;
Stack<int> stack = new Stack<int>();
stack.Push(1);
stack.Push(2);
stack.Push(3);
stack.Count; // Returns the number of elements in the stack.
// Returns the object at the top of the stack without removing it
stack.Peek();
// Removes and returns the object at the top of the stack.
stack.Pop();

3rd year - Electrical Engineering Generics and Collections in C# 13


LinkedList<T>:

▪ LinkedList is a collection of nodes where each node contains a value and


references to the previous and next nodes. It provides efficient insertion and
deletion operations.
LinkedList<int> linkedList = new LinkedList<int>();
linkedList.AddLast(1);
linkedList.AddLast(2);

linkedList.Count;

// Returns the first node in the linked list.


linkedList.First;

// Returns the last node in the linked list.


linkedList.Last;
3rd year - Electrical Engineering Generics and Collections in C# 14
HashSet<T>

▪ HashSet<T>: HashSet is a collection that stores unique elements. It provides


methods for set operations like union, intersection, and difference.

using System.Collections.Generic;
HashSet<int> uniqueNumbers = new HashSet<int>();
uniqueNumbers.Add(1);
uniqueNumbers.Add(2);
uniqueNumbers.Add(3);

// Commonly used methods and properties:


uniqueNumbers.Count;
uniqueNumbers.Contains(2);
uniqueNumbers.Remove(1);

3rd year - Electrical Engineering Generics and Collections in C# 15


SortedSet<T>

▪ SortedSet is a collection that stores unique elements in sorted order. It


automatically maintains the sort order when elements are added or removed.
SortedSet<int> sortedSet = new SortedSet<int>();
sortedSet.Add(5);
sortedSet.Add(3);
sortedSet.Add(8);

sortedSet.Count;
// Returns the number of elements in the sorted set.
sortedSet.Contains(3);
// Returns true if the sorted set contains the element 3,
otherwise false.
sortedSet.Remove(5);
// Removes the element 5 from the sorted set.
3rd year - Electrical Engineering Generics and Collections in C# 16
Selecting a Collection Class

▪ Do you need a sequential list where the element is typically discarded after its value is
retrieved?
▪ Do you need to access the elements in a certain order, such as FIFO, LIFO, or random?

▪ If yes,
▪ consider using the Queue class or the Queue<T> generic class if you need first-in,
first-out (FIFO) behavior.
▪ Consider using the Stack class or the Stack<T> generic class if you need last-in, first-
out (LIFO) behavior.
▪ the LinkedList<T> generic class allows sequential access either from the head to the
tail, or from the tail to the head.
▪ For safe access from multiple threads, use the concurrent versions,
ConcurrentQueue<T> and ConcurrentStack<T>.
▪ If not, consider using the other collections.

3rd year - Electrical Engineering Generics and Collections in C# 17


Selecting a Collection Class
▪ Do you need to access each element by index?

• The ArrayList and the List<T> generic class offer access to their elements by the zero-
based index of the element.
• The Hashtable, SortedList, and StringDictionary classes, and the Dictionary<TKey,TValue>
and SortedDictionary<TKey,TValue> generic classes offer access to their elements by the
key of the element.
• SortedList<TKey,TValue> generic classes offer access to their elements by either the zero-
based index or the key of the element.

3rd year - Electrical Engineering Generics and Collections in C# 18


Selecting a Collection Class
▪ Will each element contain one value, a combination of one key and one value, or a
combination of one key and multiple values?
▪ One value: Use any of the collections based on the IList interface or the IList<T>
generic interface. For an immutable option, consider the IImmutableList<T> generic
interface.

▪ One key and one value: Use any of the collections based on the IDictionary interface
or the IDictionary<TKey,TValue> generic interface. For an immutable option, consider
the IImmutableSet<T> or IImmutableDictionary<TKey,TValue> generic interfaces.

▪ Do you need fast searches and retrieval of information?


▪ The Dictionary<TKey,TValue> generic class provides faster lookup than the
SortedDictionary<TKey,TValue> generic class.

3rd year - Electrical Engineering Generics and Collections in C# 19


Selecting a Collection Class
▪ Do you need to sort the elements differently from how they were entered?

▪ The Hashtable class sorts its elements by their hash codes.

▪ The SortedList class, and the SortedList<TKey,TValue> and SortedDictionary<TKey,TValue>


generic classes sort their elements by the key.
▪ The sort order is based on the implementation of the IComparer interface for the
SortedList class and on the implementation of the IComparer<T> generic interface for
the SortedList<TKey,TValue> and SortedDictionary<TKey,TValue> generic classes.
▪ Of the two generic types, SortedDictionary<TKey,TValue> offers better performance
than SortedList<TKey,TValue>, while SortedList<TKey,TValue> consumes less memory.

▪ ArrayList provides a Sort method that takes an IComparer implementation as a


parameter. Its generic counterpart, the List<T> generic class, provides a Sort method that
takes an implementation of the IComparer<T> generic interface as a parameter.

3rd year - Electrical Engineering Generics and Collections in C# 20


Selecting a Collection Class

▪ If you need a collection of unique items, use a Set (HashSet).


▪ If you want to access items by index, use an Array or List.
▪ If you want to map keys to values, use a Dictionary.
▪ If you need a first-in-first-out order, use a Queue.
▪ If you need a last-in-first-out order, use a Stack.

3rd year - Electrical Engineering Generics and Collections in C# 21


Selecting a Collection Class
▪ we have collection of elements,
which data structure to select

3rd year - Electrical Engineering Generics and Collections in C# 22

You might also like