kota's memex

c sharp list

You probably are looking for lists insted. They're the equivalent of go's slice type and use arrays under the hood.

Declaration

You must specify both the type and size of the array:

string[] fraudulentOrderIDs = new string[3];
fraudulentOrderIDs[0] = "A123";
fraudulentOrderIDs[1] = "B456";
fraudulentOrderIDs[2] = "C789";

Alternatively you can initialize an array while declaring it:

string[] fraudulentOrderIDs = {"A123", "B456", "C789"};

Length

The Length property is an integer representing the length of your array.

Indexing from the end

This fetches the last item in an array. Note that it's indexed by 1 when going in reverse direction:

int lastScore = scores[^1];

Re-assignment

You cannot increase the size of an array (use lists for this purpose), but you can re-assign a new section of memory to the same variable:

int[] scores = new int[10];
scores = new int[20];

Getting a range / sub-slice

The selection is [closed, open) to in this case scores[0], scores[1], and scores[2] are selected:

int[] firstThreeScores = scores[0..3];

Looping

string[] names = {"Rowena", "Robin", "Bao"};
foreach (string name in names)
{
	Console.WriteLine(name);
}

2D (or multidimensional in general)

Declaration

int[,] matrix = new int[3,3]; // a 3x3 2D array

Accessing elements

matrix[0, 0] = 12;
int v = matrix[0, 0];

Looping

int[,] matrix = new int[4,4];

for (int row = 0; row < matrix.GetLength(0); row++)
{
  for (int column = 0; column < matrix.GetLength(1); column++)
  {
    Console.WriteLine(matrix[row, column] + " ");
  }
  Console.WriteLine();
}

## Dynamic allocation
```cs
int[][] dynamicArray = new int[n][]; // where 'n' is a variable
for (int i = 0; i < n; i++)
{
    dynamicArray[i] = new int[m]; // where 'm' is a variable
}