Skip to content

Latest commit

 

History

History
110 lines (82 loc) · 3.08 KB

File metadata and controls

110 lines (82 loc) · 3.08 KB
title Arrays and Reference Types
actions
checkAnswer
hints
material
editor
language startingCode answer
c#
public class Planets { public static void Main (string[] args) { // enter your answer here } }
public class Planets { public static void Main (string[] args) { string[] planets = { "Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune" }; Console.WriteLine (planets[3]); } }

Tag: C# Basics

Now we will take a detour from the contract itself to introduce another crucial data type: arrays.

Arrays store multiple variables of the same type in one reference. Its general form looks like this:

type[] arrayName; 

The type of an array can be value types such as int and bool, or an object, such as the object we just defined: Alien:

int[] integers = { 1, 2, 3, 4, 5 }; 
byte[] bytes = { 23, 43, 52, 15 }; 
string[] weekDays = { "Mon", "Tue", "Wed", "Thu", "Fri" }; 
Alien[] aliens = 
            {
                new Alien (12345678, "Alien1", 0), 
                new Alien (23456789, "Alien2", 1)
            }

You can access or change array members like this:

Console.WriteLine (integers[0]);  // "1"
integers[0] = 3; 
Console.WriteLine (ingeters[0]);  // "3"

Console.WriteLine (aliens[0].alienName);  // "Alien1"

Arrays Are Objects

Instances of arrays are objects, which means, you can declare arrays just like in Chapter 4, with the new keyword:

int[] integers = new int[] { 1, 2, 3 }; 

This is useful when declaring an empty array to be filled with data later.

int[] integers = new int[4]; // initialising an empty array with 4 elements. 

It also means each array has multiple fields that can be called. The most common one being Length:

string[] names = new string[4]; 
Console.WriteLine (names.Length); // "4"

Reference and Value Types

An important distinction to make in Data types is that of reference and value types. Value types store the data itself inside the variable, whereas reference types store a pointer to the data.

int i1 = 1; 
int i2 = i1; 
i2 = 2; 

Console.WriteLine (i2);  // "2"
Console.WriteLine (i1);  // "1"

In this example, i1 and i2 are value types and point to different locations in the memory.

int[] a1 = { 1, 2, 3 }; 
int[] a2 = a1; 
i2[0] = 2; 

Console.WriteLine (a2[0]);  // "2"
Console.WriteLine (a1[0]);  // "2"

In this example, the reference type a1 points to the location in memory where the array is stored. Since a2 points to the same location, changing an element in a2 means changing the same data that a1 points to.

Examples of value types: int, bool, char, struct Examples of reference types: Object, string, Class

Instructions:

An exercise for arrays:

  • In an empty program, initiate an array (planets) that contains the name all planets of the solar system.
  • Use Console.WriteLine () to print the fourth planet from the sun.