DEV Community

Stanley-Kemuel Lloyd Salvation
Stanley-Kemuel Lloyd Salvation

Posted on

C# Arrays Part 1 - Creating Arrays

Things to Note about C# arrays

  • Arrays are stored in continuous-memory locations or contiguous block of memory.
  • Arrays are index based and starts at index of zero.
  • Array size must be define
  • Array type must be defined
  • Do not add values more than defined size, e.g if size = 4 then index starts at 0 and ends at 3.

Array Declaration Snippet

type[] arrayVariableName = new type[size];

Array Example

    public class Program
    {
        static void Main(string[] args)
        {
            int[] numbers = new int[5]; // create and initialize array

            // set values in array
            numbers[0] = 52;
            numbers[1] = 63;
            numbers[2] = 44;

            // display value from array
            Console.WriteLine($"First index is {numbers[0]}");

            Console.ReadKey();
        }
    }
Enter fullscreen mode Exit fullscreen mode

Array Initializer Example

  • Using array initializer example below, you can initialize the array with values on declaration
int[] numbers = new int[5] {55, 22, 43, -1, 0};
string[] names = new string[3]{"Abel", "Marvel", "Phil"};
Enter fullscreen mode Exit fullscreen mode

Import Notes

  • Values in arrays are called elements
  • Arrays are used to hold group of values where as variables hold a single value
  • The length represents the number of properties in the array
Console.WriteLine($"Length of array {numbers.Length}");
Enter fullscreen mode Exit fullscreen mode
  • Arrays belong to the names space System.Array and are stored in the heap memory. Its address reference is stored in reference variable on the stack memory.

Top comments (0)