Generics and Collections in C#

Generics and Collections in C#

Generics and collections are fundamental concepts that are extensively used to create reusable and type-safe code for handling groups of objects. Let's explore each of these concepts with examples.


Generics in C#:

Generics in C# allow you to define classes, interfaces, and methods with placeholders for the data types they operate on. This enables you to create components that can work with any data type while maintaining type safety.

Example 1: Generic Class

public class MyGenericClass<T>
{
    private T _myField;

    public MyGenericClass(T value)
    {
        _myField = value;
    }

    public T GetValue()
    {
        return _myField;
    }
}

// Usage
MyGenericClass<int> intInstance = new MyGenericClass<int>(10);

int value = intInstance.GetValue(); 
// value will be 10

MyGenericClass<string> stringInstance =new MyGenericClass<string("Hello");

string text = stringInstance.GetValue(); 
// text will be "Hello"
        

Example 2: Generic Method

public static T GetFirstElement<T>(T[] array)
{
    if (array.Length > 0)
        return array[0];
    else
        throw new ArgumentException("Array must not be empty");
}

// Usage
int[] intArray = { 1, 2, 3 };
int firstInt = GetFirstElement(intArray); // firstInt will be 1

string[] stringArray = { "Apple", "Banana", "Orange" };
string firstString = GetFirstElement(stringArray); // firstString will be "Apple"
        

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.

In C#, the .NET Framework provides several collection types for various purposes. Here's a list of commonly used collections in C#:

  • Arrays: Arrays are the most basic collection type in C#. They have a fixed size and hold elements of the same type.

int[] numbers = new int[] { 1, 2, 3, 4, 5 };        

  • List<T>: List is a dynamic array that can grow or shrink in size. It provides methods for adding, removing, and accessing elements.

using System.Collections.Generic;

List<string> names = new List<string>();
names.Add("Alice");
names.Add("Bob");
names.Add("Charlie");

// Commonly used methods and properties:

names.Count;            
// Returns the number of elements in the list.

names.Contains("Bob"); 
// Returns true if "Bob" is found in the list, otherwise false.

names.Remove("Alice"); 
// Removes the first occurrence of "Alice" from the list.
        

  • 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:

ages.Count;               
// Returns the number of key-value pairs in the dictionary.

ages.ContainsKey("Bob"); 
// Returns true if the dictionary contains the key "Bob", otherwise false.

ages.Remove("Alice");    
// Removes the entry with the key "Alice" from the dictionary.
        

  • 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;       
// Returns the number of elements in the set.

uniqueNumbers.Contains(2); 
// Returns true if the set contains the element 2, otherwise false.

uniqueNumbers.Remove(1);   
// Removes the element 1 from the set.
        

  • 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");

// Commonly used methods and properties:

queue.Count;           
// Returns the number of elements in the queue.

queue.Peek();          
// Returns the object at the beginning of the queue without removing it.

queue.Dequeue();       
// Removes and returns the object at the beginning of the queue.
        

  • 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);

// Commonly used methods and properties:

stack.Count;      
// Returns the number of elements in the stack.

stack.Peek();     
// Returns the object at the top of the stack without removing it.

stack.Pop();      
// Removes and returns the object at the top of the stack.
        

  • 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.

using System.Collections.Generic;

LinkedList<int> linkedList = new LinkedList<int>();
linkedList.AddLast(1);
linkedList.AddLast(2);
linkedList.AddLast(3);

// Commonly used methods and properties:

linkedList.Count;    
// Returns the number of elements in the linked list.

linkedList.First;    
// Returns the first node in the linked list.

linkedList.Last;     
// Returns the last node in the linked list.
        

  • 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.

using System.Collections.Generic;

SortedSet<int> sortedSet = new SortedSet<int>();
sortedSet.Add(5);
sortedSet.Add(3);
sortedSet.Add(8);

// Commonly used methods and properties:

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.
        

  • Queue: Queue is a non-generic collection that follows the FIFO principle.

using System.Collections;

Queue queue = new Queue();
queue.Enqueue("First");
queue.Enqueue("Second");
queue.Enqueue("Third");

// Commonly used methods and properties:

queue.Count;      
// Returns the number of elements in the queue.

queue.Peek();     
// Returns the object at the beginning of the queue without removing it.

queue.Dequeue();  
// Removes and returns the object at the beginning of the queue.
        

  • Stack: Stack is a non-generic collection that follows the LIFO principle.

using System.Collections;

Stack stack = new Stack();
stack.Push(1);
stack.Push(2);
stack.Push(3);

// Commonly used methods and properties:

stack.Count;     
// Returns the number of elements in the stack.

stack.Peek();    
// Returns the object at the top of the stack without removing it.

stack.Pop();     
// Removes and returns the object at the top of the stack.
        

  • Hashtable: Hashtable is a non-generic collection that stores key-value pairs similar to Dictionary<TKey, TValue>.

using System.Collections;

Hashtable hashtable = new Hashtable();
hashtable.Add("Alice", 30);
hashtable.Add("Bob", 35);
hashtable.Add("Charlie", 40);

// Commonly used methods and properties:
hashtable.Count;      // Returns the number of key-value pairs in the hashtable.
hashtable.ContainsKey("Bob"); // Returns true if the hashtable contains the key "Bob", otherwise false.
hashtable.Remove("Alice");    // Removes the entry with the key "Alice" from the hashtable.
        

  • 12. ArrayList: ArrayList is a non-generic collection that dynamically resizes itself to accommodate new elements.

using System.Collections;

ArrayList arrayList = new ArrayList();
arrayList.Add("Alice");
arrayList.Add("Bob");
arrayList.Add("Charlie");

// Commonly used methods and properties:
arrayList.Count;        // Returns the number of elements in the array list.
arrayList.Contains("Bob"); // Returns true if "Bob" is found in the array list, otherwise false.
arrayList.Remove("Alice"); // Removes the first occurrence of "Alice" from the array list.
        

These are some of the commonly used collection types in C#. Each collection type has its own characteristics and is suitable for different scenarios.


Volodymyr Haievyi

C# developer, Azure cloud engineer | 19+ years in .NET | 10+ years in Full Stack

1 年

Thanks for sharing. The generics are super convenient for many cases. It is worth mentioning the disadvantages of generics: * Too many generic types lead to maintenance complexity. * Generics may lead to code bloat. * Debugging generic code can sometimes be more challenging than non-generic code since generics are resolved at compile time; understanding the types that are being used at runtime can sometimes require more effort. * While constraints in generics allow you to specify requirements for the type parameters, they are still limited. For instance, you cannot specify a constraint for a specific constructor.

要查看或添加评论,请登录

Vikram .的更多文章

社区洞察

其他会员也浏览了