Lesson 7 - Variables and Data Types

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

Previous Article  |  Next Article


In this lesson, we're going to examine variables and data types more closely. We briefly looked at these coding concepts in Lesson 3 - Building Your First Web App, where it was mentioned that variables are like named “buckets” that store values of the type declared, and that values can be retrieved from. Let’s revisit, and expand on this concept by looking once again at the code within the MyFirstWebApp project.

Step 1: Declaring Variables and Assigning Values

In the okButton_Click code block, a variable is first declared with an arbitrary name, firstName, and the type of information it that can store, string. The string variable is a type of "bucket" that can hold just enough information for what it holds: alphanumeric characters. firstName is then assigned the string value contained in another variable called firstNameTextBox.Text:

cs-asp-007---variables-and-data-types.001

Tip:

Strings are just one of many, many variable types in C#. If you think of variable types as buckets, as we've explained previously, you can easily visualize the need for a specific type of "bucket" for every data type that needs to be stored. A bucket meant to hold numbers cannot hold letters, for example. C# offers different "buckets" (variable types) for every different purpose.

In the above example, we are completing two separate operations on a single line of code. The first step declares the variable type (what size of "bucket"), as well as its unique name (identifier) that can be used to reference it elsewhere in code. This step simply sets aside an empty “bucket” in memory that is large enough to store a string value, and labels this bucket with a name that uniquely identifies it:

cs-asp-007---variables-and-data-types.002

The next step takes that “bucket” and puts a value into it; in this case, an existing string:

cs-asp-007---variables-and-data-types.003

You can, of course, write out these steps on separate lines, which would look something like this:

cs-asp-007---variables-and-data-types.004

While "name" could be any sequence of alphanumeric characters, we chose the literal string “Bob” to make the two-step process clearer. In this case, we initialize the variable "name" by immediately giving it a literal string ("Bob"), whereas earlier we retrieved the value of another variable and set that value to firstName (this is closer to what you saw in the original example above):

cs-asp-007---variables-and-data-types.005

Be careful when declaring variables. It is perfectly acceptable to reference already declared variables, however, you cannot re-declare already declared variables. Here we (1) declared firstName, then (2) referenced it by assigning a value to it, but (3) erroneously re-declared the same variable we declared in (1) To fix this, simply remove the type declaration (string) in (3) and it would be valid C# syntax:

cs-asp-007---variables-and-data-types.006

Step 2: Understanding Variables as “Buckets”

The first two lines of code here can be visualized, using the “bucket” analogy, as looking something like this:

cs-asp-007---variables-and-data-types.007

In the above code, you will notice how the variable called “name,“ is later referenced by taking the value that it currently holds (“Bob”) and assigning it, via the equal’s assignment operator, into the variable called “firstName“:

cs-asp-007---variables-and-data-types.008

This is a hint as to the versatility you get by creating a variable identifier for referencing throughout your code (such as, in this case, not having to constantly write out the literal string “Bob”). The result of this assignment operation, (taking the value held in name and placing it into firstName) can be visualized as follows:

cs-asp-007---variables-and-data-types.009

Note that the “bucket” variable dumping its value into another bucket (via the assignment operator) still holds on to the value itself. In other words, "firstName" can be thought of as copying the value within name, so that "name" and "firstName" both hold the literal string "Bob":

cs-asp-007---variables-and-data-types.010

Step 3: Understanding Variable Naming Limitations

A variable identifier can be labeled as anything you choose, with a few general limitations. The identifier should:

  • Be at least one alphabetical character.

  • Not start with a number.

  • Not contain non-alpha-numerical characters other than dash and underscore.

  • Not contain any spaces.

  • Not be exactly the same as a reserved word in C#.

While this might seem like a lot to remember, Visual Studio will tell you when your variable is not named correctly by producing a red squiggly line, indicating an error:

cs-asp-007---variables-and-data-types.011

Step 4: Adding Comments in Code

You will also get a green squiggly line, indicating a warning, when you declare a variable that is never made use of. Here, we commented out the line of code that makes use of the variable called "name", leading to a warning:

cs-asp-007---variables-and-data-types.012

You can also comment out multiple lines of code, using /* and *\ as follows:

cs-asp-007---variables-and-data-types.013

Tip:

Commenting out code tells the compiler to ignore the line entirely. Commenting can be useful for a number of reasons

  • Adding a note to yourself, or others who may read your code.
  • Removing parts of your code in order to track down problems.
  • Preserving code that you don’t want to throw out entirely, yet has no current use (think code that fulfills some occasional testing purpose, yet shouldn’t be in the final build).

Step 5: Primitive C# Data Types

We already know that a string is a sequence of alpha-numerical characters (numbers and letters) but there are many other primitive, pre-defined data types in C# that hold whole numbers, decimal numbers, characters, true/false values, and so on:

Variable Types

Tip:

The main reason for these different sized “buckets” is generally for sake of economy. In other words, don’t use a bucket large enough to hold a quintillion-sized number (long) when all you need is a tiny bucket, big enough to hold a number up to a few thousand (short). This helps your application to run much more efficiently, and reduces stress on the server and the user's machine.

Step 6: Uninitialized Variable Default Values

Here are the default values for uninitialized variables (those that are declared, but not yet given any value by using the assignment operator):

  • Whole number data types (byte, sbyte, short, ushort, int, uint, long, ulong) – 0

  • Decimal number data types (float, double, decimal) – 0.0

  • string data types – “” (empty string)

  • bool data types – False

  • char data types – null

Tip:

This may seem like a rather large list of basic types to keep track of. However, in general the basic data types that you will really need to remember are string, int, double and bool.

Work on remembering the difference between these different data types, and the importance of putting the right information into the right "bucket". You will use variables very often when programming, so knowing these concepts is going to be very helpful to you moving forward. Good job, we'll see you in the next lesson!


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