Lesson 8 - Data Type Conversion

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

Previous Article  |  Next Article


Get GitHub Code

When programming, there are times that you need to reference a data type in a variable of another type. In these instances, you will need to convert from one data type into another. In this lesson, you will learn how to perform some basic data type conversions, as we touch upon common situations requiring this – most notably when receiving user input from Server Controls via the Web Form.

Step 1: Create a New Project

To demonstrate this, go ahead and set up a new ASP.NET project called “CS-ASP_008”. And using the steps detailed in “003 – Building Your First Web App” create a Default.aspx with TextBox, Button, and Label Server Controls with the following programmatic IDs:

  1. inputTextBox

  2. okButton

  3. resultLabel

Make sure to clear the Text property of the resultLabel and to set the Text property of the okButton to "Go".

cs-asp-008---data-type-conversions.001

Step 2: Understanding Data Type Assignment Mismatch

Then go to the Default.aspx.cs file and write the following in the okButton_Click code block:

cs-asp-008---data-type-conversions.002

Notice that the literal string “Hello World” becomes underlined with a red squiggly line. This indicates a compilation error, where the application will not run, as opposed to the green squiggly that denotes a warning. That’s because we’re trying to put a string (alphanumeric characters) into a variable that is only able to hold an int (integer/whole number) value:

cs-asp-008---data-type-conversions.003

Tip:

If you hover over the underlined text, Visual Studio will give you a hint as to why it ran into an error. In this case, hovering over the underlined string will say “Error: Cannot implicitly convert type string to int.” Error messages – when they aren’t cryptic – will often be helpful towards tracking down the problem.

Step 3: Implicit Conversions

Implicit conversions can often be done between similar data types. However, a string and an int are completely different from one another. It’s not immediately obvious what it would mean to convert a bunch of letters into a number, even if we were to do something like this:

cs-asp-008---data-type-conversions.006

In such cases, where two data types are so fundamentally different, an explicit conversion will be needed instead (which we will get to in a moment). By contrast, an example of a simple, implicit conversion would be in the event of an upcast. Taking a smaller data type and converting it to a larger data type of the same base value format. For example, an int and a long are data types that both store whole numbers. The only difference is that a long can simply store a much larger number than an int. Upcasting in this scenario would be like taking the contents of a smaller bucket and putting it into a larger bucket:

cs-asp-008---data-type-conversions.007

cs-asp-008---data-type-conversions.008

However, this kind of implicit conversion can’t be done downcasting from a larger bucket into a smaller bucket, even though each bucket stores the same basic value format. The extra data from the larger bucket, can’t fit into the smaller bucket regardless of their type:

cs-asp-008---data-type-conversions.009

cs-asp-008---data-type-conversions.010

Step 4: Explicit Conversion via Casting

Even though an implicit conversion is not possible in this scenario, you can perform an explicit casting operation on the long variable j. This conversion effectively shrinks j down to an int before we attempt to copy its contents over to the int variable i. This explicit conversion process is possible because the underlying data types are both whole numbers. Casting is very simple is accomplished by prefixing the variable that you want to convert - with the type you want to convert to - enclosed in parentheses:

cs-asp-008---data-type-conversions.011

Tip:

There are ramifications of performing the cast operation. By doing so you, the programmer, are taking control and overriding Visual Studio's default behavior, which is to not allow a downcast from a larger type into a smaller type. An unintended error/exception or data loss might occur in certain cases.

Step 5: Double to Int Truncation

Note that in the above example, we were able to cast j to an int without data loss because an int can hold an integer value up to 2,147,483,647. If, on the other hand, j held a number larger than that, it simply would not fit into int i and would yield a totally different result than we were expecting. Let’s consider a similar scenario where we try to do an explicit conversion between a double and an int. We see that this is possible, in principle, as the compiler doesn’t show any errors:

cs-asp-008---data-type-conversions.013

However, we know that an int won’t be able to represent the decimal place, as it can only represent whole numbers. Let’s try to output this in our resultLabel to see the result of casting k to an int:

cs-asp-008---data-type-conversions.014

Step 6: Convert to String via ToString() Helper Method

We see this error when trying to copy the integer value from i into the string value for resultLabel.Text. You may be tempted to try something like this:

cs-asp-008---data-type-conversions.015

However, that doesn’t work because casting is possible only between similar underlying data types. You would be forgiven for thinking that 2.5 and “2.5” are not terribly different. They may be of different data types, but the only real difference is one is in quotes while the other one isn’t. Fortunately, there are helper methods (we will cover methods in depth in later lessons) that can handle conversions such as these that are simple in nature, yet can’t be done with explicit casting. In this case, we will want to access the ToString() method, that you can find as an option when using Intellisense and the “dot accessor” (period) after the variable:

cs-asp-008---data-type-conversions.016

Be sure to invoke the helper method by inputting empty parentheses after the method name. This step is necessary when using helper methods:

cs-asp-008---data-type-conversions.017

When you run the application, and click the “Go” button, here is what you will see:

cs-asp-008---data-type-conversions.018

This is an example of the kind of error/data loss that can occur when casting. In this case, casting from double k to int i truncated (cut off) whatever the decimal value would have been, owing to the fact that an int simply won’t recognize decimal values.

Tip:

Truncating a value is very different from rounding a value to the nearest whole number. Truncation simply chops off the decimal value as if it never existed. Truncating can be very useful in many circumstances, but can also cause problems in your code if it was not the result you anticipated.

Going back to the application, let’s allow the user to type in a number, perform a calculation on that number, and then display the result. We know ahead of time that at least two conversions will have to take place:

  1. The TextBox Control stores user input into a string, so we will want to convert that string to an int in order to perform a calculation on it.

  2. The Label Control stores the result as a string, so we will want to convert the result of the int calculation back into a string.

Step 7: String to Int via int.Parse() Helper Method

We already saw that you can’t cast an int to a string. So, instead, we use a helper method to perform the conversion:

cs-asp-008---data-type-conversions.020

Tip:

This looks a little bit different from the ToString() helper method we saw when going from an int to a string, but the same principle is in effect. The main difference is that the Parse() helper method comes from inside of the int class and takes in a string as input, in between the method parentheses. This will all become much clearer when we delve into methods a bit later.

Now that we have the user input stored as an integer in int j, we can safely perform a calculation on that integer:

cs-asp-008---data-type-conversions.022

And then to display this through our Label Control, we simply convert k to a string, as we did before:

cs-asp-008---data-type-conversions.023

Now, when we run the application we see the process worked as intended:

cs-asp-008---data-type-conversions.024

At this point, you may be tempted to see what happens when you input a value that can’t be converted to an integer, for instance:

cs-asp-008---data-type-conversions.025

Step 8: Failed Conversion Runtime Error

If you attempt to do that, a runtime exception/error will occur, and Visual Studio will inform you with exactly what line of code failed. Unsurprisingly, it was the line that attempted to convert the string to an int. Essentially, int.Parse() will only work when the string looks exactly like a number, and nothing more:

cs-asp-008---data-type-conversions.026

Tip:

Unlike other errors we've seen so far, runtime errors cannot be caught by the compiler. We’ve seen how compile-time errors will be caught by Visual Studio, and warn you with a red squiggly line before you try and run your application. By contrast, runtime errors can linger in your code until they are discovered through rigorous testing, or else a user-submitted bug report.

The way to combat this situation is to perform some validation that checks if that the user provided input in the correct format. Validation requires some logic that we are not yet ready to get into yet, but note that we will come back to this issue in a later lesson. For now, focus on the conversions we've covered this far. Great job, and keep it up!


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