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#:
int[] numbers = new int[] { 1, 2, 3, 4, 5 };
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.
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.
领英推荐
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.