Square brackets ([]) are used for arrays, indexers, and attributes. They can also be used with pointers. Example code for potion strength.
# Using Arrays in C#
using System;
class Program
{
static void Main()
{
// Declare and initialize an array
int[] numbers = { 1, 2, 3, 4, 5 };
// Access elements using index
Console.WriteLine(numbers[0]); // Output: 1
Console.WriteLine(numbers[4]); // Output: 5
// Modify elements using index
numbers[2] = 10;
Console.WriteLine(numbers[2]); // Output: 10
// Iterate through the array
foreach (int number in numbers)
{
Console.WriteLine(number);
}
}
}
C# 8.0 now has ranges and indices which makes it easier to access subarrays or elements.
// C# Ranges and Index
using System;
class Program
{
static void Main()
{
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// Using indices
Console.WriteLine(numbers[^1^](https://learn.microsoft.com/en-us/dotnet/csharp/tutorials/ranges-indexes)); // Output: 10 (last element)
Console.WriteLine(numbers[^2^](https://www.programiz.com/csharp-programming/indexer)); // Output: 9 (second last element)
// Using ranges
int[] subArray = numbers[2..5]; // Elements from index 2 to 4
foreach (int number in subArray)
{
Console.WriteLine(number); // Output: 3, 4, 5
}
int[] lastThree = numbers[^3..]; // Last three elements
foreach (int number in lastThree)
{
Console.WriteLine(number); // Output: 8, 9, 10
}
}
}