Introduction:
In the previous post, we explored control structures in C#, including if/else statements, switch statements, and various looping constructs (for, while, and do/while). In this post, we'll delve into arrays and collections, which are essential data structures for storing and manipulating groups of related data items. After this article, we'll move on to the next chapter: "Object-Oriented Programming with C#."
Arrays:
An array is a fixed-size, ordered collection of elements of the same data type. The elements in an array can be accessed by their index, which starts from zero.
Creating and Initializing Arrays:
There are multiple ways to create and initialize arrays in C#. Here are some common examples:
-
Declare an array with a specified size:
int[] numbers = new int[5];
-
Declare and initialize an array with specific values:
int[] numbers = { 1, 2, 3, 4, 5 };
-
Declare and initialize an array using the new keyword and an array initializer:
int[] numbers = new int[] { 1, 2, 3, 4, 5 };
Accessing Array Elements:
You can access individual array elements using their index:
int firstNumber = numbers[0]; // Access the first element of the array int lastNumber = numbers[numbers.Length - 1]; // Access the last element of the array
Collections:
Collections are a set of classes in the System.Collections and System.Collections.Generic namespaces that provide more flexible and powerful ways to store and manipulate data compared to arrays. Some commonly used collections are:
List<T>: A dynamically-sized, ordered collection of elements.
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
Dictionary<TKey, TValue>: A collection of key-value pairs, where each key is unique.
Dictionary<string, int> ages = new Dictionary<string, int> { { "Alice", 30 }, { "Bob", 25 } };
HashSet<T>: An unordered collection of unique elements.
HashSet<int> uniqueNumbers = new HashSet<int> { 1, 2, 2, 3, 4, 4, 5 };
Stack<T> and Queue<T>: Collections that represent the Last-In-First-Out (LIFO) and First-In-First-Out (FIFO) data structures, respectively.
Stack<int> stack = new Stack<int>(); Queue<int> queue = new Queue<int>();
Conclusion:
In this article, we covered the basics of arrays and collections in C#, including how to create, initialize, and manipulate these data structures. Arrays and collections are fundamental to storing and working with data in a wide range of applications.
In the next chapter, we'll dive into "Object-Oriented Programming with C#," where we'll explore concepts such as classes, objects, inheritance, polymorphism, and more. Stay tuned for more C# learning!
Comments
Post a Comment