Mastering Collections and Generics in C#

When working with C#, understanding collections and generics is fundamental for creating efficient, reusable, and maintainable code. This blog post dives into the essentials of these concepts, including arrays, dictionaries, lists, LINQ, and memory management techniques.
Collections in C#
Collections are versatile structures used to store and manage groups of data. C# offers several types of collections, including arrays, dictionaries, lists, and LINQ queries. Each serves a unique purpose and fits specific use cases.
Arrays
Arrays are fixed-size collections best used when the size of the list can be determined at design time. They can be multidimensional or arrays of arrays, making them flexible for many scenarios. Best practices for arrays include:
- Use plural variable names to indicate their nature (e.g.,
colorOptions
). - Avoid manual population; always initialize arrays.
Combine declaration and initialization for brevity:
string[] colorOptions = new string[4];
var colorOptions = new string[4];
Arrays derive from the System.Array
class, allowing the use of built-in methods for operations like sorting or searching.
Lists
Lists manage groups of items dynamically, expanding as needed. They’re one-dimensional and allow insertion, addition, or removal of elements. Use lists when the size of the collection is unknown at design time. Key points include:
- Use
List<T>
to define the type of items stored. - Prefer
Add
for appending elements andInsert
for placing elements at specific positions.
Use LinkedList
if the list changes frequently:
var colorOptions = new List<string>();
colorOptions.Add("Red");
colorOptions.Insert(2, "Purple");
colorOptions.Remove("White");
Dictionaries
Dictionaries store key-value pairs and are ideal when each item requires a unique identifier. Items are retrieved by their key:
var stateAbbreviations = new Dictionary<string, string>();
stateAbbreviations.Add("NV", "Nevada");
Dictionaries ensure fast lookups and are especially useful for mapping data.
Generics
Generics allow the creation of reusable, type-neutral classes and methods, enhancing code flexibility while maintaining type safety. Use generics when the exact data type isn’t known upfront.
Key Features of Generics:
- Use
T
to define a type parameter in classes or methods. - Add constraints to type parameters for specificity:
where T : struct
(value type)where T : class
(reference type)where T : new()
(parameterless constructor)where T : Vendor
(specific class or derived type)
Example:
public class OperationResult<T>
{
public T Result { get; set; }
}
public T RetrieveValue<T>(string sql, T defaultValue)
{
// Implementation
}
Advanced Concepts
LINQ
Language-Integrated Query (LINQ) provides powerful capabilities for querying collections in a readable, declarative manner. LINQ works seamlessly with arrays, lists, and other enumerable collections, offering methods like Where
, Select
, and GroupBy
.
Delegates and Lambda Expressions
Delegates are type-safe pointers to methods, often used in event handling. Lambda expressions simplify the syntax for defining delegates, making the code concise and expressive.
Memory Management: Garbage Collection vs. Dispose()
Managed code in C# relies on the Common Language Runtime (CLR) for automatic memory management. CLR provides garbage collection, which cleans up unused objects. However, for managing unmanaged resources, implement the IDisposable
interface and use the Dispose
method explicitly.
Application Lifecycle
C# applications have an Application_Start
method that runs only when the first user accesses the page. This behavior ensures efficient resource use and can be customized using the App_Start
folder and WebActivator.
Conclusion
Mastering collections and generics in C# opens up new possibilities for writing efficient, reusable, and maintainable code. From selecting the right collection type to leveraging generics and LINQ, these tools are essential for any developer aiming to build robust applications. Keep exploring, and apply these best practices to your next project!