Lesson 21 - Storing Values in 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 storing values in arrays. The concept is not very difficult to understand if you think about “bucket” analogy we used to describe variables in previous lessons. An array is essentially a collection of values, under a single variable name, that all have the same value types, yet can hold distinct values. You can visualize an array as a row of buckets hanging from a broom-handle:

cs-asp-021---storing-values-in-arrays.001

In this illustration, we “imprint” on the broom-handle the variable type that all the buckets must conform to, and initialize it with the number of distinct buckets we’re allowed to store values in. We can then reference the individual buckets in our code by referring to the index. Arrays are indexed starting from 0 and can hold as many individual buckets as you need (as long as itd doesn't exceed the amount specified in when you initialize it). Here is how we would represent this particular array illustration:

cs-asp-021---storing-values-in-arrays.002

Note that the array can hold only one data type (here, it is of type int), and the empty square brackets after the data type tells the compiler that this is, in fact, an array. The array must always be initialized with the “new” keyword, along with the data type and the size of the array (the amount of individual “buckets” specified in the brackets). Once you have values in each “bucket” you can reference them just as you would with any variable, except now you have to include the particular array element you want to use at any given moment:

cs-asp-021---storing-values-in-arrays.003


Tip:

Arrays are simple to create, however, they are extremely powerful. The simplest use of an array is to just group values that seem like they should belong together in some way. But the most common use for arrays is to iterate through them, performing some operation on each individual value. That leads us into loops, where arrays are often the star of the show. You’ll see this in action in later lessons.

Step 1: Create a New Project

Let’s start by creating a new ASP.NET project called “CS-ASP_021” and create the following Controls and programmatic IDs:

  1. TextBox1

  2. TextBox2

  3. TextBox3

  4. TextBox4

  5. TextBox5

  6. addButton

  7. retrieveButton

  8. resultLabel

cs-asp-021---storing-values-in-arrays.006

Now, write this code in the addButton_Click event to create the array and then display the third element upon clicking the button:

cs-asp-021---storing-values-in-arrays.007

Step 2: Arrays Indexes Start at [0]

Keeping in mind that the [2] index is the third value (since the index starts at [0]) we would expect the third TextBox entry to be output, via the resultLabel, after clicking the “Add” button:

cs-asp-021---storing-values-in-arrays.008

Step 3: Using the Length Property to Count Array Size

Go back to the addButton_Click event and take a look at the variety of methods and properties available to the array. A common property is Length, which returns how many individual array elements there are, as an integer:

cs-asp-021---storing-values-in-arrays.009

Let’s reference this property in code, so that we can see it displayed when clicking the “Add” button. We know ahead of time that this particular array has five elements:

cs-asp-021---storing-values-in-arrays.010

cs-asp-021---storing-values-in-arrays.011

You will see the use of the Length property in later lessons when iterating through arrays and needing to determine how many times the iteration has to execute (once for each array element, typically).

Step 4: Simplifying Array Syntax with Initializers

When initializing an array with individual values for each element, there is an easier way than you’ve already seen. You can write the initial values, for each index, in curly braces right where the variable is first declared, and assigned:

cs-asp-021---storing-values-in-arrays.012

Now, combining this with what we learned about ViewState in the previous lesson, let’s add this array to the ViewState Dictionary and then retrieve values in the array by clicking on the retrieveButton_Click event:

cs-asp-021---storing-values-in-arrays.013

Pay particular attention to the line that assigns the value held in ViewState[“MyValues”] to the string[] values variable. A cast, to string[], is needed here to make it work because the array actually gets stored in the dictionary as a generic object, which cannot implicitly be converted to a string. Now, when you run the application add the names to the ViewState by clicking on the “Add” button:

cs-asp-021---storing-values-in-arrays.014

And, then display the values back, from the ViewState:

cs-asp-021---storing-values-in-arrays.015

Step 5: Referencing an Out-Of-Range Index in an Array

Perhaps the most common error programmers face when working with arrays is referencing an index that is out of range. In this case, we have an array with five indexes (numbered 0 to 4) so if we were to attempt to read from an index that does not exist we would get an IndexOutOfRangeException:

cs-asp-021---storing-values-in-arrays.016

This error also commonly occurs when trying to write a value to an index range that doesn’t exist. Here again, we only have five individual indexes numbered 0 to 4, yet we’re trying to access a non-existent sixth index at values[5]:

cs-asp-021---storing-values-in-arrays.017

Tip:

You may find it troublesome trying to remember which individual array value belongs to which particular index. This is made a bit more difficult owing to the fact that indexes start at [0]. There is a good computational reason for this being the case. It may be annoying, but soon you will get used to remembering that the highest index for your array is one less than the actual number of elements in your array.

Arrays are a very useful tool that can help you to store multiple values quickly and easily, then retrieve them in code when you need them. Keep them in mind as we'll be using them frequently throughout this course. Great job!


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