An array is a collection of elements of the same type.
Declaration
string[] friends;
string[] friends = new string[100];
double[] accounts = [ 1000.50, 999.99, 2530.02 ];
Accessing Elements:
friends[0] = "Alice";
string firstFriend = friends[0];
Limitations:
int i = 0;
while (i < games.Length)
{
Console.WriteLine(games[i]);
i++;
}
for (int i = 0; i < games.Length; i++)
{
Console.WriteLine(games[i]);
}
Console.Write("Enter the number of games: ");
int numGames = Convert.ToInt32(Console.ReadLine());
string[] games = new string[numGames];
List<string> games = new List<string>();
games.Add("Sonic Adventure");
string firstGame = games[0];
List<int> stats = [ 99, 72, 33 ];
Simplifies iteration over collections by accessing each element directly without using indexes.
Syntax:
foreach (var item in collection)
{
// Use item
}
Example with Array:
foreach (string fruit in fruits)
{
Console.WriteLine("I like to eat " + fruit);
}
Example with List:
foreach (int number in numbers)
{
Console.WriteLine(number);
}
Usage Guidelines:
Add(item)
: Adds an item to the end of the list.AddRange(list)
: Add the elements of a specified collection to the end of a list.Clear()
: Removes all elements from the list.Contains(item)
: Checks if an item exists in the list.IndexOf(item)
: Returns the index of the item, or -1 if not found.Insert(index, item)
: Inserts an item at the specified index.Remove(item)
: Removes the first occurrence of the item.RemoveAt(index)
: Removes the item at the specified index.Reverse()
: Reverses the order of elements.Sort()
: Sorts the elements in ascending order.Value Types:
int a = 5;
int b = a;
b = 10; // a remains 5
Reference Types:
List<int> list1 = new List<int> [ 1, 2, 3 ];
List<int> list2 = list1;
list2[0] = 99; // Both list1 and list2 reflect the change
Important Note:
for
, while
, foreach
) are essential for iterating over collections efficiently.