Lesson 22 - Understanding Multidimensional Arrays

Tutorial Series: Free C# Fundamentals via ASP.NET Web Apps

Previous Article  |  Next Article


Get GitHub Code

In this lesson, we're going to talk about multidimensional arrays. Multidimensional arrays are exactly like single-dimensional arrays, with the difference being that they require more than one index to get at a single element. Think of a grid or spreadsheet. In order to retrieve the value you want from a cell in a spreadsheet you need to know both the row and column numbers that correspond to the cell. Also, each index - except for the last one (the one that contains a value/object) - is itself an array.

Step 1: Create a Two-Dimensional Array

The simplest multidimensional array would be a two-dimensional array, which means it would have two indexes:

cs-asp-022---understanding-multidimensional-arrays.001

Here, MyArray is declared on the first line as being an array that holds three compartments, which in turn each holds another three compartments with the actual value inside of them.

Each group (arbitrarily separated with white space for clarity) can be seen as the first level compartment, while the next level is the group that stores the actual value. To access the values, you can reference them with the indexes they reside in:

cs-asp-022---understanding-multidimensional-arrays.002

Step 2: Visualizing a Two-Dimensional Array as a Data Table

You can also visualize this entire data/organization relationship as being like a common table structure:

cs-asp-022---understanding-multidimensional-arrays.003

This is similar to a multiplication table, where you get the value (in the grid) by matching up the row number with the column number. Unfortunately, this visual is limited when dealing larger multidimensional arrays, such as a three-dimensional array.

Step 3: Create a Three-Dimensional Array

Here is an example of an array with three dimensions:

cs-asp-022---understanding-multidimensional-arrays.004

Step 4: Visualizing Multi-Dimensional Arrays as Containers

This type of structure looks more complicated, but it only has one more level of sub-containment, and is best visualized as successive containers that contain other containers. Notice, again, how only the last level of containment holds an actual value while the other levels are only sub-containers:

cs-asp-022---understanding-multidimensional-arrays.005

Tip:

While this containment structure may seem unintuitive, there are a plethora of analogous structures in the world we live in. Take, for example, a house. Each house represents the outer-most container, which contains individual rooms as sub-containers. And in each room there may be drawers, boxes, or cabinets that act as sub-sub-containers. Instead of using indexes - as we do in C# - we label these containers with names and effortlessly locate items of value with simple phrases like “In Joe’s house, there is Amanda’s room, and in that room is a cabinet that holds an Xbox controller.”

Step 5: A Real-World Containment Analogy

If you are having difficulty visualizing the containment structure for the array, temporarily replace each index with a familiar containment structure, such as the following:

cs-asp-022---understanding-multidimensional-arrays.008

Obviously, this will cause a compilation error (hence the red underlines), however, it should hopefully make the basic containment concept more intelligible. In this example there are:

  • Two separate rooms

    cs-asp-022---understanding-multidimensional-arrays.009

  • Three separate organizers in each room

    cs-asp-022---understanding-multidimensional-arrays.010

  • Three separate compartments in each organizer

    cs-asp-022---understanding-multidimensional-arrays.011

And, of course, in each compartment is the actual value of relevance (in this analogy, the number of items in the compartment). In the illustration below, we’re representing 4 items in the “Socks” compartment within the “Dresser” organizer, inside of the “MasterBedroom”:

cs-asp-022---understanding-multidimensional-arrays.012

Also, notice how the number of dimensions is specified with the comma delimiter (empty for the type declaration, populated at initial assignment):

cs-asp-022---understanding-multidimensional-arrays.013

Step 6: Create a New Project

Now, let’s put into action what we’ve learned about multi-dimensional arrays by creating an ASP.NET project called “CS-ASP_022” and create the following Controls and programmatic IDs:

  1. fromChicagoRadio

  2. fromNewYorkRadio

  3. fromLondonRadio

  4. toChicagoRadio

  5. toNewYorkRadio

  6. toLondonRadio

  7. okButton

  8. resultLabel


cs-asp-022---understanding-multidimensional-arrays.014


What this application will do is let us hold various prices for travelling:

  • From Chicago to New York

  • From Chicago to London

  • From New York to Chicago

  • From New York to London

  • From London to Chicago

  • From London to New York

Step 7: Storing Travel Prices in a Two-Dimensional Array

We can represent these various prices with a simple two-dimensional array, populating it on page load:

cs-asp-022---understanding-multidimensional-arrays.015

To access the price of traveling from New York to London, we simply reference it with the relevant indexes that we populated with values:

cs-asp-022---understanding-multidimensional-arrays.016

cs-asp-022---understanding-multidimensional-arrays.017

Step 8: Broadening a Variable’s Scope

Currently, priceGrid becomes populated in the Page_Load event, but what if we wanted to access these values via the okButton_Click event? You could, of course, put all of the code in the okButton_Click event, or you could even save it in the ViewState. However, supposing those solutions are not satisfactory, here is a much easier way of letting both events make reference to priceGrid. Simply move the declaration of priceGrid to the class level, as follows:

cs-asp-022---understanding-multidimensional-arrays.018

Tip:

This leads us towards the topic of code scope. This will be covered in the following lessons lessons. However, for now just know that the squiggly brackets indicate a level of scope. By declaring a variable in an outer scope, it can be accessed by any inner scope. In this case, the outer scope is public class Default, while the inner scopes are the Page_Load and okButton_Click events, respectively.

Now, you can also access priceGrid from within okButton_Click, and set the values upon clicking the radio buttons:

cs-asp-022---understanding-multidimensional-arrays.020

Step 9: Adding Logic to Ignore the Same Source/Destination City

Note that the last conditional statement simply exits the entire code block (with the return keyword) before anything would display on the screen on the next line of code. This has the effect of doing nothing if selecting the same city for source/destination. When you run the application you will now be able to select various sources and destinations, and press “OK” to retrieve the applicable value:

cs-asp-022---understanding-multidimensional-arrays.021

Step 10: Clear Out the ResultLabel

You may have noticed that the resultLabel isn’t cleared under the condition of having the same city for source and destination. That’s because the method is exited (returned) out of before the resultLabel can be written to. And if a value in resultLabel was already present from a previous button submission this could cause confusion. Let’s ensure that nothing is displayed in the resultLabel when the source/destination are the same:

cs-asp-022---understanding-multidimensional-arrays.022

Tip:

While arrays are quite powerful, you will probably not need to use multi-dimensional arrays very much in your programming career. They are very useful for holding particular data organization, whether that’s something to do with multi-dimensional space, or complex database structures. However, there is another – arguably more useful - concept closely related to arrays and that is Collections. You will learn about Collections in later lessons, but basically they are built from arrays and are easier to handle due to being more flexible/less strict.


Related Articles in this Tutorial:

Lesson 1 - Series Introduction

Lesson 2 - Installing Visual Studio 2015

Lesson 3 - Building Your First Web App

Lesson 4 - Understanding What You Just Did

Lesson 5 - Working with Projects in Visual Studio

Lesson 6 - Simple Web Page Formatting in Visual Studio

Challenge 1

Solution 1

Lesson 7 - Variables and Data Types

Lesson 8 - Data Type Conversion

Lesson 9 - Arithmetic Operators

Lesson 10 - C# Syntax Basics

Challenge 2 - ChallengeSimpleCalculator

Solution - ChallengeSimpleCalculator

Lesson 11 - Conditional If Statements

Lesson 12 - The Conditional Ternary Operator

Challenge 3 - ChallengeConditionalRadioButton

Solution - Challenge Conditional RadioButton

Lesson 13 - Comparison and Logical Operators

Lesson 13 Challenge - First Papa Bob's Website

Solution - Challenge First Papa Bob's Website

Lesson 14 - Working with Dates and Times

Lesson 15 - Working With Spans of Time

Lesson 16 - Working with the Calendar Server Control

Challenge 4 - Challenge Days Between Dates

Solution - Challenge Days Between Dates

Lesson 17 - Page_Load and Page.IsPostBack

Lesson 18 - Setting a Break Point and Debugging

Lesson 19 - Formatting Strings

Challenge 5 - Challenge Epic Spies Assignment

Solution - Challenge Epic Spies Assignment

Lesson 20 - Maintaining State with ViewState

Lesson 21 - Storing Values in Arrays

Lesson 22 - Understanding Multidimensional Arrays

Lesson 23 - Changing the Length of an Array

Challenge 6 - Challenge Epic Spies Asset Tracker

Solution - Challenge Epic Spies Asset Tracker

Lesson 24 - Understanding Variable Scope

Lesson 25 - Code Blocks and Nested If Statements

Lesson 26 - Looping with the For Iteration Statement

Challenge 7 - Challenge For Xmen Battle Count

Solution - Challenge For Xmen Battle Count

Lesson 27 - Looping with the while() & do...while() Iteration Statements

Lesson 28 - Creating and Calling Simple Helper Methods

Lesson 29 - Creating Methods with Input Parameters

Lesson 30 - Returning Values from Methods

Lesson 31 - Creating Overloaded Methods

Lesson 32 - Creating Optional Parameters

Lesson 33 - Creating Names Parameters

Lesson 34 - Creating Methods with Output Parameters

Challenge 8 - Challenge Postal Calculator Helper Methods

Solution - Challenge Postal Calculator Helper Methods

Mega Challenge Casino

Solution - Mega Challenge Casino

Lesson 35 - Manipulating Strings

Challenge 9 - Phun With Strings

Solution - Challenge Phun With Strings

Lesson 36 - Introduction to Classes and Objects

Challenge - Hero Monster Classes Part 1

Solution - Hero Monster Classes Part 1

Challenge - Hero Monster Classes Part 2

Solution - Challenge Hero Monster Classes Part 2

Lesson 37 - Creating Class Files Creating Cohesive Classes and Code Navigation

Lesson 38 - Understanding Object References and Object Lifetime

Lesson 39 - Understanding the .NET Framework and Compilation

Lesson 40 - Namespaces and Using Directives

Lesson 41 - Creating Class Libraries and Adding References to Assemblies

Lesson 42 - Accessibility Modifiers, Fields and Properties

Lesson 43 - Creating Constructor Methods

Lesson 44 - Naming Conventions for Identifiers

Lesson 45 - Static vs Instance Members

Challenge 10 - Challenge Simple Darts

Solution - Challenge Simple Darts

Lesson 46 - Working with the List Collection

Lesson 47 - Object Initializers

Lesson 48 - Collection Initializers

Lesson 49 - Working with the Dictionary Collection

Lesson 50 - Looping with the foreach Iteration Statement

Lesson 51 - Implicitly-Typed Variables with the var Keyword

Challenge 11 - Challenge Student Courses

Solution - Challenge Student Courses

Mega Challenge War

Solution - Mega Challenge War

Lesson 52 - Creating GUIDs

Lesson 53 - Working with Enumerations

Lesson 54 - Understanding the switch() Statement

Lesson 55 - First Pass at the Separation of Concerns Principle

Lesson 56 - Understanding Exception Handling

Lesson 57 - Understanding Global Exception Handling

Lesson 58 - Understanding Custom Exceptions

Lesson 59 - Creating a Database in Visual Studio

Lesson 60 - Creating an Entity Data Model

Lesson 61 - Displaying the DbSet Result in an ASP.NET GridView

Lesson 62 - Implementing a Button Command in a GridView

Lesson 63 - Using a Tools-Centric Approach to Building a Database Application

Lesson 64 - Using a Maintenance-Driven Approach to Building a Database Application

Lesson 65 - Creating a New Instance of an Entity and Persisting it to the Database

Lesson 66 - Package Management with NuGet

Lesson 67 - NuGet No-Commit Workflow

Lesson 68 - Introduction the Twitter Bootstrap CSS Framework

Lesson 69 - Mapping Enum Types to Entity Properties in the Framework Designer

Lesson 70 - Deploying the App to Microsoft Azure Web Services Web Apps

Papa Bob's Mega Challenge

Papa Bob's Mega Solution Part 1 - Setting up the Solution

Papa Bob's Mega Solution Part 2 - Adding an Order to the Database

Papa Bob's Mega Solution Part 3 - Passing an Order from the Presentation Layer

Papa Bob's Mega Solution Part 4 - Creating the Order Form

Papa Bob's Mega Solution Part 5 - Adding Enums

Papa Bob's Mega Solution Part 6 - Creating an Order with Validation

Papa Bob's Mega Solution Part 7 - Calculating the Order Price

Papa Bob's Mega Solution Part 8 - Displaying the Price to the User

Papa Bob's Mega Solution Part 9 - Creating the Order Management Page


Comments

Please login or register to add a comment