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.
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:
Make sure to clear the Text property of the resultLabel and to set the Text property of the okButton to "Go".
Then go to the Default.aspx.cs file and write the following in the okButton_Click code block:
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:
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.
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:
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:
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:
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:
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.
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:
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:
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:
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:
Be sure to invoke the helper method by inputting empty parentheses after the method name. This step is necessary when using helper methods:
When you run the application, and click the “Go” button, here is what you will see:
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.
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:
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.
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.
We already saw that you can’t cast an int to a string. So, instead, we use a helper method to perform the conversion:
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:
And then to display this through our Label Control, we simply convert k to a string, as we did before:
Now, when we run the application we see the process worked as intended:
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:
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:
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!
Lesson 8 - Data Type Conversion