This tutorial will guide you through the process of working with Arrays and Lists in the C# programming language. The aim is to provide you with a thorough understanding of how to declare, initialize, and manipulate these data structures.
By the end of this tutorial, you will be able to:
- Understand the difference between Arrays and Lists
- Declare and Initialize Arrays and Lists
- Manipulate data stored in Arrays and Lists
Prerequisites:
- Basic knowledge of C# programming language
- A text editor for writing code (Visual Studio, Visual Studio Code, Notepad++, etc.)
- .NET framework installed on your machine
An array is a data structure that stores elements of the same type. In C#, arrays are objects.
// declaring an array
int[] arrayName;
// initializing an array
arrayName = new int[5]; // array with 5 integer elements
Array elements are accessed using their index, starting from 0.
int firstElement = arrayName[0]; // accessing the first element
A List, unlike an array, is a dynamic data structure, meaning it can grow and shrink in size during runtime.
// declaring and initializing a List
List<int> listName = new List<int>();
// adding an element
listName.Add(1);
// removing an element
listName.Remove(1);
int[] numbers = new int[3]; // Declare and initialize an array with 3 elements
// Assign values to the array
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
// Print the second element of the array
Console.WriteLine(numbers[1]); // Outputs: 20
List<int> numbers = new List<int>(); // Declare and initialize a List
// Add values to the list
numbers.Add(10);
numbers.Add(20);
numbers.Add(30);
// Print the second element of the list
Console.WriteLine(numbers[1]); // Outputs: 20
In this tutorial, we've covered the basics of working with Arrays and Lists in C#. You should now be able to declare, initialize, and manipulate data stored in these data structures.
To further your understanding, try out different operations on these data structures like searching elements, sorting, etc. Refer to Microsoft's official documentation for more details on Arrays and Lists in C#.
Declare an array of 5 integers, assign values to it, and print the third element.
int[] numbers = new int[5] {1, 2, 3, 4, 5}; // Declare and initialize an array
Console.WriteLine(numbers[2]); // Outputs: 3
Declare a list of strings, add three names to it, and remove the second name.
List<string> names = new List<string>(); // Declare and initialize a List
names.Add("John");
names.Add("Jane");
names.Add("Joe");
names.RemoveAt(1); // Remove the second name
foreach(string name in names)
{
Console.WriteLine(name); // Outputs: John Joe
}
Keep practicing and experimenting with these data structures to get a solid grasp. Happy coding!