Working with Arrays and Collections in C#: A Beginner's Guide
Learning how to work with arrays and collections in C# is a key step in becoming a confident C# developer. These structures help you store, organize, and manipulate data efficiently — whether you’re managing a list of numbers, student names, or product details.
What Are Arrays in C#?
An array in C# is a collection of elements of the same type stored in a contiguous memory location. You can think of it as a fixed-size container that holds values such as numbers or strings.
Declaring and Initializing Arrays in C#
There are several ways to declare and initialize an array. Here’s how:
// Declaration and initialization
int[] numbers = new int[5]; // Creates an array with 5 integer elements
// Initialize with values
int[] scores = { 90, 80, 70, 85, 95 };
// Using the new keyword with values
string[] names = new string[] { "Alice", "Bob", "Charlie" };
This code demonstrates how to declare and initialize arrays in C#. Arrays are zero-indexed, meaning the first element starts at index 0.
Accessing and Modifying Array Elements
You can access elements using their index number:
int firstScore = scores[0]; // Access the first element
scores[1] = 88; // Modify the second element
Console.WriteLine(scores[1]); // Output: 88
Be careful not to access an index outside the array’s range — it will cause an IndexOutOfRangeException.
Iterating Through Arrays Using foreach Loop
The foreach loop is ideal for reading array elements:
foreach (int score in scores)
{
Console.WriteLine(score);
}
This loop makes your code cleaner and avoids dealing with index numbers manually.
Introduction to Collections in C#
Unlike arrays, collections in C# are dynamic — they can grow or shrink in size. The System.Collections.Generic namespace provides several powerful collection types for handling data efficiently.
Common Collection Types in C#
1. List<T> in C#
The List in C# is a dynamic array that allows adding, removing, and iterating over items.
using System;
using System.Collections.Generic;
class Example
{
static void Main()
{
List<string> fruits = new List<string>() { "Apple", "Banana", "Cherry" };
fruits.Add("Mango");
foreach (string fruit in fruits)
{
Console.WriteLine(fruit);
}
}
}
2. Dictionary<TKey, TValue> in C#
A Dictionary in C# stores key-value pairs and is useful for fast lookups.
Dictionary<int, string> students = new Dictionary<int, string>()
{
{ 1, "John" },
{ 2, "Emma" },
{ 3, "Liam" }
};
Console.WriteLine(students[2]); // Output: Emma
3. HashSet<T>
A HashSet stores unique values and ignores duplicates.
HashSet<int> uniqueNumbers = new HashSet<int>() { 1, 2, 2, 3 };
foreach (int num in uniqueNumbers)
{
Console.WriteLine(num); // Output: 1, 2, 3
}
4. Queue<T>
A Queue follows the First-In-First-Out (FIFO) principle.
Queue<string> tasks = new Queue<string>();
tasks.Enqueue("Task 1");
tasks.Enqueue("Task 2");
Console.WriteLine(tasks.Dequeue()); // Output: Task 1
When to Use Arrays vs Collections
| Scenario | Use |
|---|---|
| Fixed number of elements | Array |
| Need dynamic resizing | List<T> |
| Need key-value mapping | Dictionary<TKey, TValue> |
| Need only unique items | HashSet<T> |
| Need FIFO order | Queue<T> |
Conclusion
Arrays and collections form the backbone of data handling in C#. Arrays provide simplicity and performance for fixed-size data, while collections like List, Dictionary, and Queue give flexibility for dynamic data operations. Understanding when and how to use each makes your code cleaner, faster, and more maintainable.
Ready to take the next step? Check out related posts like:
- Understanding Data Types and Variables in C#
- Mastering Conditional Statements and Loops in C#
- Getting Started with Methods and Functions in C#
- Object-Oriented Programming Concepts in C#
Call to Action: Continue practicing by building small programs that use arrays and collections. The more you experiment, the more confident you’ll become with C# data structures!
This Content Sponsored by SBO Digital Marketing. Mobile-Based Part-Time Job Opportunity by SBO! Earn money online by doing simple content publishing and sharing tasks. Here's how: Job Type: Mobile-based part-time work Work Involves: Content publishing Content sharing on social media Time Required: As little as 1 hour a day Earnings: ₹300 or more daily Requirements: Active Facebook and Instagram account Basic knowledge of using mobile and social media For more details: WhatsApp your Name and Qualification to 9025032394 a.Online Part Time Jobs from Home b.Work from Home Jobs Without Investment c.Freelance Jobs Online for Students d.Mobile Based Online Jobs e.Daily Payment Online Jobs Keyword & Tag: #OnlinePartTimeJob #WorkFromHome #EarnMoneyOnline #PartTimeJob #jobs #jobalerts #withoutinvestmentjob


0 Comments